‘distinct() groupwise’的直接方法

问题描述 投票:0回答:1

我想做同样的事情

distinct()
,但对于团体来说。这是一个例子:

data <- data.frame(
  group = c(1, 1, 2, 3, 3, 4, 4, 5, 5),
  procedure = c("A", "B", "A", "A", "B", "A", "X", "A", "X")
)

  group procedure
1     1         A
2     1         B
3     2         A
4     3         A
5     3         B
6     4         A
7     4         X
8     5         A
9     5         X

我期待这个:

 group procedure group_id
  <dbl> <chr>              <int>
1     1 A                      2
2     1 B                      2
3     2 A                      1
4     4 A                      3
5     4 X                      3

我使用这个工作代码:

library(dplyr)
library(tidyr)

data %>%
  summarise(procedure = toString(sort(procedure)), .by = group) %>%
  mutate(group_id = as.integer(factor(procedure))) %>% 
  distinct(group_id, .keep_all = TRUE) %>% 
  separate_rows(procedure)

有没有更直接的方法?对于上下文,我的数据集包含 23,000 行,其中有许多组,我需要识别和评估每个组的主要成员。因此,我正在寻找一种有效区分和评估所有独特群体的方法。您能否建议一种促进此评估的方法?

r tidyverse distinct group
1个回答
0
投票

假设

group_id
只是一个临时列而不是预期的输出,我们可以通过非欺骗来
split
subset

> split(data, ~group) |> 
+   subset(!lapply(., `[[`, 2) |> sapply(toString) |> duplicated()) |> 
+   do.call(what='rbind')
    group procedure
1.1     1         A
1.2     1         B
2       2         A
4.6     4         A
4.7     4         X
© www.soinside.com 2019 - 2024. All rights reserved.