如何基于列表列中的值筛选DataFrame(R语言)
解决嵌套列表列的筛选问题
问题核心
你原代码中filter(df, "thing 3" %in% problem)无效的原因是:%in%会将整个problem列(一个嵌套列表)作为整体检查,而非逐行判断每个子列表是否包含目标值,因此只会返回单个逻辑值,无法正确筛选行。下面提供几种无需拆列的高效解法:
1. dplyr + purrr 解法
利用purrr::map_lgl逐行遍历problem列的每个子列表,返回逻辑向量供filter使用:
library(dplyr) library(purrr) # 构造数据 problem <- list(list("thing 1", "thing 2"), list("thing 1", "thing 2", "thing 3"), list("thing 1")) df <- data.frame(name = c("joe", "sue", "nancy"), problem = I(problem)) # 筛选包含"thing 3"的行 df %>% filter(map_lgl(problem, ~"thing 3" %in% .x))
2. data.table 解法
转为data.table后,在i参数中用vapply(比sapply更高效安全)逐行判断:
library(data.table) dt <- as.data.table(df) # 筛选目标行 dt[vapply(problem, function(x) "thing 3" %in% x, logical(1))]
如果追求更简洁的写法,也可以用sapply:
dt[sapply(problem, function(x) "thing 3" %in% x)]
3. Base R 解法
直接用subset或逻辑索引结合sapply:
# 方法1:subset函数 subset(df, sapply(problem, function(x) "thing 3" %in% x)) # 方法2:直接逻辑索引 df[sapply(problem, function(x) "thing 3" %in% x), ]
内容的提问来源于stack exchange,提问作者Joshua Hill
相关产品推荐
相关产品推荐

