【问题标题】:dplyr: Difference between unique and distinctdplyr:独特和独特之间的区别
【发布时间】:2015-05-22 16:01:49
【问题描述】:

使用 distinct 与 unique 时,结果行数似乎不同。我正在使用的数据集非常庞大。希望代码可以理解。

dt2a <- select(dt, mutation.genome.position, 
  mutation.cds, primary.site, sample.name, mutation.id) %>%
  group_by(mutation.genome.position, mutation.cds, primary.site) %>% 
  mutate(occ = nrow(.)) %>%
  select(-sample.name) %>% distinct()
dim(dt2a)
[1] 2316382       5

## Using unique instead
dt2b <- select(dt, mutation.genome.position, mutation.cds, 
   primary.site, sample.name, mutation.id) %>%
  group_by(mutation.genome.position, mutation.cds, primary.site) %>%
  mutate(occ = nrow(.)) %>%
  select(-sample.name) %>% unique()
dim(dt2b)
[1] 2837982       5

这是我正在使用的文件:

sftp://sftp-cancer.sanger.ac.uk/files/grch38/cosmic/v72/CosmicMutantExport.tsv.gz

     dt = fread(fl)

【问题讨论】:

  • 这可能需要您做一些工作,但一个小的可重现示例会更好。
  • 对于小型数据集,两者给出的答案相同。

标签: r data.table dplyr


【解决方案1】:

这似乎是group_by 考虑这种情况的结果

dt<-data.frame(g=rep(c("a","b"), each=3),
    v=c(2,2,5,2,7,7))

dt %>% group_by(g) %>% unique()
# Source: local data frame [4 x 2]
# Groups: g
# 
#   g v
# 1 a 2
# 2 a 5
# 3 b 2
# 4 b 7

dt %>% group_by(g) %>% distinct()
# Source: local data frame [2 x 2]
# Groups: g
# 
#   g v
# 1 a 2
# 2 b 2

dt %>% group_by(g) %>% distinct(v)
# Source: local data frame [4 x 2]
# Groups: g
# 
#   g v
# 1 a 2
# 2 a 5
# 3 b 2
# 4 b 7

当您使用distinct() 而不指明要区分哪些变量时,它似乎使用了分组变量。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多