如何检查一列的唯一值对于 R 中另一列的不同值是否多次出现?

How can I check if unique values of a column has multiple occurrences for different values of another column in R?

示例数据:

set.seed(4)
cl <- sample(LETTERS[1:2], 100, replace = T)
seller <- round(runif(100, min=1, max=80))

df <- data.frame(cl, seller)

    cl seller
1    B     21
2    A     51
3    A     22
4    A     43
5    A     38
6    B     46
7    A     54
8    B     18
9    A     78
.......

99   A     32
100  B      8

我想检查 seller 的一个唯一值在 AB 中出现的次数。假设,在具有此特定种子的数据框中,您会看到 A 和 B 都出现了 7,因此将计算 7。

我的尝试:

df %>%
  filter(cl=='A')-> d1

df %>%
  filter(cl=='B')-> d2

d3 <- merge(d1, d2, by='seller') %>%
  distinct(seller)

nrow(d3)
17

因此,有 17 个卖家同时拥有分类:A 和 B。

到目前为止,我的尝试并不是最理想的。它产生了结果,但是必须有更好的方法 dplyr 甚至我无法弄清楚的基础 R 。另外,如果我这样做的话,对于更大的数据集来说会非常耗时。

我怎样才能更好、更整洁地解决这个问题?

我们可以使用 n_distinct(假设只有 'A'、'B' 值在 'cl' 列中找到):

library(dplyr)
df %>%
    group_by(seller) %>%
    summarise(n = n_distinct(cl), .groups = 'drop') %>%
    filter(n == 2) %>%
    nrow

输出:

[1] 17

或者也可以

df %>%
    group_by(seller) %>%
    summarise(n = all(c("A", "B") %in% cl), .groups = 'drop') %>%
    pull(n) %>%
    sum
[1] 17

使用 tablecolSumssum

的基础 R 方法
sum(colSums(table(df) > 0) == 2)
#[1] 17