首页 > 解决方案 > 如何选择非唯一的列组合?

问题描述

我的数据如下所示:

counts <- data.frame(
  pos = c(101, 101, 101, 102, 102, 102, 103, 103, 103, 101, 101, 101),
  chr = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4),
  subj = c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C")
)

pos应该只属于一个 unique chr,但这里 pos 101 属于 chr 1 和 4。

我可以像这样检测这种情况:

counts %>% select(pos, chr) %>%
  group_by(pos) %>%
  summarise(n_chrs = length(unique(chr))) %>%
  filter(n_chrs > 1)

这将返回pos具有多于 to 的chr值:

 A tibble: 1 x 2
    pos n_chrs
  <dbl>  <int>
1   101      2

我想知道chr涉及哪些值,例如:

  pos chr
1 101   1
2 101   4

谢谢!

标签: rdplyr

解决方案


你可以这样做:

library(dplyr)

counts %>%
  group_by(pos) %>%
  distinct(chr) %>%
  filter(n() > 1)

输出:

# A tibble: 2 x 2
# Groups:   pos [1]
    pos   chr
  <dbl> <dbl>
1   101     1
2   101     4

推荐阅读