Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Renaming a single element in a list transforms the names of the other elements to `<NA>`

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading