访问列表中的 NA 字段

Access the NA field in the list

我们可以轻松地在 R 列表中创建一个 NA name/field。
但是很难访问这个 NA 字段。
我想从循环中访问列表中的 NA 字段名称。

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)

这是我的一些丑陋的解决方案:

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

您可以在列表的 names

上使用 match
lapply(c("a","a", "b", NA), \(x) ll[[match(x, names(ll))]])
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 1
#> 
#> [[3]]
#> [1] 2
#> 
#> [[4]]
#> [1] 4