首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在数据帧中,查找给定列[R]中仅包含一定值(等于)的组。

在数据帧中,查找给定列[R]中仅包含一定值(等于)的组。
EN

Stack Overflow用户
提问于 2022-04-07 12:18:45
回答 2查看 29关注 0票数 0

我想获得一个包含组名(ID)的向量,其中某些列(类)只包含一种类型的值(A)。换句话说:我想检查组是否只包含给定列(类)中的给定值(A) -如果它们包含了,我想收集这个组的名称。

下面是两个虚拟数据文件:

代码语言:javascript
运行
复制
ID <- c(rep("first", 4), rep("second", 5), rep("third", 3))
segment <- c(1,2,6,7,1,2,3,4,6,1,4,5)
class <- c(rep("A", 6), "G", rep("A", 5))

df1 <- data.frame(ID, segment, class)

ID <- c(rep("first", 4), rep("second", 5), rep("third", 3))
segment <- c(1,2,6,7,1,2,3,4,6,1,4,5)
class <- c(rep("A", 6), "G", rep("A", 2), rep("B", 3))

df2 <- data.frame(ID, segment, class)

下面是我的解决方案:

代码语言:javascript
运行
复制
output_grouped_by_ID <- df2 %>% dplyr::group_by(ID) %>% 
dplyr::mutate(identical = n_distinct(class)==1 & class=="A") %>%
dplyr::filter(identical==FALSE)
uniq <- unique(output_grouped_by_ID$ID)

有没有更快的方式使用基础R或data.table?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-07 12:24:25

R基中的下列一行应该是相对较快的:

代码语言:javascript
运行
复制
names(which(sapply(split(df1$class, df1$ID), function(x) all(x == 'A'))))
#> [1] "first" "third"

这比目前的方法快一个数量级以上:

代码语言:javascript
运行
复制
method_sapply <- function() {
  names(which(sapply(split(df1$class, df1$ID), function(x) all(x == 'A'))))
}

method_dplyr <- function() {
  output_grouped_by_ID <- df1 %>% dplyr::group_by(ID) %>% 
    dplyr::mutate(identical = n_distinct(class)==1 & class=="A") %>%
    dplyr::filter(identical==FALSE)
    unique(output_grouped_by_ID$ID)
}

microbenchmark::microbenchmark(method_sapply(), method_dplyr())
#>Unit: microseconds
#>            expr    min      lq     mean  median      uq    max neval cld
#> method_sapply()   53.6   70.70  110.513   78.75   93.40 2836.0   100  a 
#>  method_dplyr() 3330.8 3575.85 3934.029 4020.45 4175.95 7232.1   100   b
票数 1
EN

Stack Overflow用户

发布于 2022-04-07 13:18:12

使用tapply

代码语言:javascript
运行
复制
names(which(with(df2, tapply(class, ID, unique) != 'A')))
# [1] "second" "third" 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71782061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档