簡體   English   中英

如何根據列表列中的值對 dataframe 進行子集化

[英]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))

  • Output
  name      problem
2  sue thing 1,....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM