gpt4 book ai didi

r - 如果另一列包含特定值集,则使用 R 中的 dplyr 过滤列

转载 作者:行者123 更新时间:2023-12-02 03:54:12 25 4
gpt4 key购买 nike

在下面的数据框中,我想过滤包含人员“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))

或者使用基础R

v1 <- rowSums(table(df)[, c('a', 'b', 'c')]>0)==3
subset(df, group %in% names(v1)[v1])

更新

如果我们只想使用 dplyr 返回 2

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]

关于r - 如果另一列包含特定值集,则使用 R 中的 dplyr 过滤列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44486602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com