如果另一列包含特定的一组值,则使用 R 中的 dplyr 过滤一列
Filter a column if another column contains specific set of values using dplyr in R
在下面的数据框中,我想过滤包含人 "a"、"b" 和 "c" 的组:
df <- structure(list(group = c(1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4),
person = structure(c(1L, 2L, 1L, 3L, 1L, 2L, 3L, 1L, 1L,
2L, 3L, 4L), .Label = c("a", "b", "c", "e"), class = "factor")), .Names =
c("group",
"person"), row.names = c(NA, -12L), class = "data.frame")
我们可以使用data.table
。将'data.frame'转换为'data.table'(setDT(df)
),按'group'分组,我们通过检查all
是否为'a',得到逻辑索引,'b', 'c' 元素是 %in%
'person' 得到 Data.table (.SD
)
的子集
library(data.table)
setDT(df)[, .SD[all(c('a', 'b', 'c') %in% person)], group]
或 dplyr
,按 'person'
分组后使用相同的方法
df %>%
group_by(group) %>%
filter(all(c('a', 'b', 'c') %in% person))
或 base R
v1 <- rowSums(table(df)[, c('a', 'b', 'c')]>0)==3
subset(df, group %in% names(v1)[v1])
更新
如果我们只想 return 2
组使用 dplyr
df %>%
group_by(group) %>%
filter(all(c('a', 'b', 'c') %in% person), all(person %in% c('a', 'b', 'c')))
或 n_distinct
df %>%
group_by(group) %>%
filter(all(c('a', 'b', 'c') %in% person), n_distinct(person)==3)
或 data.table
setDT(df)[, .SD[all(c('a', 'b', 'c') %in% person) & uniqueN(person)==3], group]
在下面的数据框中,我想过滤包含人 "a"、"b" 和 "c" 的组:
df <- structure(list(group = c(1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4),
person = structure(c(1L, 2L, 1L, 3L, 1L, 2L, 3L, 1L, 1L,
2L, 3L, 4L), .Label = c("a", "b", "c", "e"), class = "factor")), .Names =
c("group",
"person"), row.names = c(NA, -12L), class = "data.frame")
我们可以使用data.table
。将'data.frame'转换为'data.table'(setDT(df)
),按'group'分组,我们通过检查all
是否为'a',得到逻辑索引,'b', 'c' 元素是 %in%
'person' 得到 Data.table (.SD
)
library(data.table)
setDT(df)[, .SD[all(c('a', 'b', 'c') %in% person)], group]
或 dplyr
,按 'person'
df %>%
group_by(group) %>%
filter(all(c('a', 'b', 'c') %in% person))
或 base R
v1 <- rowSums(table(df)[, c('a', 'b', 'c')]>0)==3
subset(df, group %in% names(v1)[v1])
更新
如果我们只想 return 2
组使用 dplyr
df %>%
group_by(group) %>%
filter(all(c('a', 'b', 'c') %in% person), all(person %in% c('a', 'b', 'c')))
或 n_distinct
df %>%
group_by(group) %>%
filter(all(c('a', 'b', 'c') %in% person), n_distinct(person)==3)
或 data.table
setDT(df)[, .SD[all(c('a', 'b', 'c') %in% person) & uniqueN(person)==3], group]