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