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

Access the NA field in the list

We could easily create a NA name/field in the R list.
However it is very hard to access this NA field.
I want to access the NA field name in the list from the loop.

ll = list(1, 2, 4)
# One name is a NA
names(ll) <- c("a", "b", NA)
# or
# ll = list(a = 1, b = 2, `NA` = 4) here "NA" works
# the only way I could access NA field in the list
ll$`NA`

# not works
ll[[NA]]
ll[NA]

# my objective is to be able to subset NA field in the loop like:
# these NOT work
ll[c("a","a", "b", NA)]
lapply(c("a","a", "b", NA), \(x) ll[[x]])
lapply(c("a","a", "b", NA), \(x) ll$x)

This some ugly solution from me:

Map(\(x) if (is.na(x)) ll$`NA` else ll[[x]], names(ll))

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

>Solution :

You can use match on the list’s names

lapply(c("a","a", "b", NA), \(x) ll[[match(x, names(ll))]])
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 1
#> 
#> [[3]]
#> [1] 2
#> 
#> [[4]]
#> [1] 4
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