![](/img/trans.png)
[英]How to subset a dataframe with a conditional statement based on multiple column values
[英]How to subset a dataframe based on values in a list column
我遇到了一個問題,我從 API 中提取信息,並且特定列中有嵌套值。 我需要過濾這些值以返回我需要的信息。 這是一個例子:
library(dplyr)
# Make Data
problem <- list(list("thing 1", "thing 2"), list("thing 1", "thing 2", "thing 3"), list("thing 1"))
name <- list("joe", "sue", "nancy")
df<-data.frame(name=c("joe", "sue", "nancy"),problem=I(problem))
# How can I find subset rows where the problem column contains "thing 3"
filter(df, name == "sue") # this works fine
filter(df, "thing 3" %in% problem) # this doesn't
對我來說很明顯,這是因為列表是嵌套的,並且 filter() 沒有“看到”數據,但我不太清楚如何繞過它。 此外,我返回的數據相當大,並且列中的每個列表都有任意數量的項目,所以如果可以避免的話,我不想取消嵌套列。
#EDIT:我沒有與 dplyr 解決方案結婚,事實上,如果有 data.table 解決方案,我會特別有興趣聽到它,但我對基礎或其他什么都很好!
任何幫助,將不勝感激。
df %>%
filter(map_lgl(problem, ~any('thing 3' == .x)))
name problem
1 sue thing 1,....
Base R
subset
subset(df , grepl("thing 3" , problem))
name problem
2 sue thing 1,....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.