R dplyr.筛选包含一列数值向量的数据框 [英] R dplyr. Filter a dataframe that contains a column of numeric vectors
问题描述
我有一个数据框,其中一列包含数值向量.我想根据涉及该列的条件来过滤行.这是一个简化的示例.
I have a dataframe in which one column contains numeric vectors. I want to filter rows based on a condition involving that column. This is a simplified example.
df <- data.frame(id = LETTERS[1:3], name=c("Alice", "Bob", "Carol"))
mylist=list(c(1,2,3), c(4,5), c(1,3,4))
df$numvecs <- mylist
df
# id name numvecs
# 1 A Alice 1, 2, 3
# 2 B Bob 4, 5
# 3 C Carol 1, 3, 4
我可以使用诸如mapply之类的东西
I can use something like mapply e.g.
mapply(function(x,y) x=="B" & 4 %in% y, df$id, df$numvecs)
第二行正确返回TRUE,第一行和第二行返回FALSE.
which correctly returns TRUE for the second row, and FALSE for rows 1 and 2.
但是,我有理由要使用dplyr过滤器而不是mapply,但是我无法使dplyr过滤器在numvecs列上正确运行.而不是返回两行,下面的命令不返回任何行.
However, I have reasons why I'd like to use dplyr filter instead of mapply, but I can't get dplyr filter to operate correctly on the numvecs column. Instead of returning two rows, the following returns no rows.
filter(df, 4 %in% numvecs)
# [1] id numvecs
# <0 rows> (or 0-length row.names)
我在这里想念什么?如何过滤涉及numvecs列的条件表达式?
What am I missing here? How can I filter on a conditional expression involving the numvecs column?
理想情况下,我也想使用非标准评估filter_,因此我可以将过滤条件作为参数传递.任何帮助表示赞赏.谢谢.
And ideally I'd like to use the non-standard evaluation filter_ as well, so I can pass the filter condition as an argument. Any help appreciated. Thanks.
推荐答案
我们仍然可以将 mapply
与 filter
filter(df, mapply(function(x,y) x == "B" & 4 %in% y, id, numvecs))
# id name numvecs
#1 B Bob 4, 5
或使用 purrr
library(purrr)
filter(df, unlist(map(numvecs, ~4 %in% .x)))
# id name numvecs
#1 B Bob 4, 5
#2 C Carol 1, 3, 4
或者我们也可以连锁进行
Or we can also do this in chain
df %>%
.$numvecs %>%
map( ~ 4 %in% .x) %>%
unlist %>%
df[.,]
# id name numvecs
#2 B Bob 4, 5
#3 C Carol 1, 3, 4
这篇关于R dplyr.筛选包含一列数值向量的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!