1

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>?

bretauv
  • 7,756
  • 2
  • 20
  • 57

1 Answers1

4

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) <- rep("", length(foo))
names(foo)[2] <- "some_name"
foo
# [[1]]
# [1] 1
# 
# $some_name
# [1] 2
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 2
    `names(foo) <- ""` results in `names(foo)` equal to the vector `"", NA`, so you need `names(foo) <- rep("", length(foo))` to set all names to `""`. – Andrew Gustar Aug 14 '23 at 17:19
  • 1
    @AndrewGustar Good point. I just got lucky with the small example. I've updated the answer. Kind of surprised recycling didn't happen in that case. – MrFlick Aug 14 '23 at 17:20