I have an unnamed list like this one:
foo <- list(1, 2)
foo
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
If I try to name only one element of this list, then the other name becomes <NA>:
names(foo)[2] <- "some_name"
foo
#> $<NA>
#> [1] 1
#>
#> $some_name
#> [1] 2
But having a mix of named and unnamed elements is possible in a list:
list(1, some_name = 2)
#> [[1]]
#> [1] 1
#>
#> $some_name
#> [1] 2
The answers to this question only show how to rename all the elements of a list, or how to rename some elements of a list that is already fully named.
How can I rename a single element of a list without transforming the other ones to <NA>?
>Solution :
When you don’t give a name, it uses the name of "" but when you use names()[2]<- it fills missing values with NA. You could get what you want by setting all values to "" first.
foo <- list(1, 2)
names(foo) <- ""
names(foo)[2] <- "some_name"
foo
# [[1]]
# [1] 1
#
# $some_name
# [1] 2