我有这个角色矢量:
fruits <- c("melon", "grapefruit", "blueberry")
我也有这个清单:
list_fruits <- list(list(first = "orange", second = NULL, third = "pineapple"),
list(first = "apple", second = NULL, third = "melon"))
list_fruits
[[1]]
[[1]]$first
[1] "apple"
[[1]]$second
NULL
[[1]]$third
[1] "pineapple"
[[2]]
[[2]]$first
[1] "apple"
[[2]]$second
NULL
[[2]]$third
[1] "melon"
如果fruits
的任何元素与third
中的任何列表list_fruits
相同,我需要first
的{{1}}列表输出为一个字符向量。
因此,如果我在list_fruits
上运行该函数,则输出为:
list_fruits
答案 0 :(得分:5)
使用sapply
sapply(list_fruits, function(X) if(X$third %in% fruits) X$first)
[[1]]
NULL
[[2]]
[1] "apple"
如果列表变得非常大,您可能希望采用另一种方法来提高效率 - 但这取决于列表其余部分的外观。
答案 1 :(得分:2)
一衬垫:
lapply(list_fruits[sapply(list_fruits, "[[", "third") %in% fruits], "[[", "first")
答案 2 :(得分:1)
也许那样?
first_fruit <- vapply(list_fruits, `[[`, character(1L), "first")
third_fruit <- vapply(list_fruits, `[[`, character(1L), "third")
first_fruit[match(fruits, third_fruit)]
# [1] "apple" NA NA
as.character(na.omit(first_fruit[match(fruits, third_fruit)]))
# [1] "apple"
答案 3 :(得分:1)
转换list_fruits
结构,然后再简化:
dat <- do.call(rbind,list_fruits)
dat[which(dat[,'third'] %in% fruits),'first']
$first
[1] "apple"