我想获得一个包含组名(ID)的向量,其中某些列(类)只包含一种类型的值(A)。换句话说:我想检查组是否只包含给定列(类)中的给定值(A) -如果它们包含了,我想收集这个组的名称。
下面是两个虚拟数据文件:
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)下面是我的解决方案:
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?
发布于 2022-04-07 12:24:25
R基中的下列一行应该是相对较快的:
names(which(sapply(split(df1$class, df1$ID), function(x) all(x == 'A'))))
#> [1] "first" "third"这比目前的方法快一个数量级以上:
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 bhttps://stackoverflow.com/questions/71782061
复制相似问题