【问题标题】:Concatenate strings by group with dplyr for multiple columns [duplicate]使用 dplyr 按组连接字符串以用于多列 [重复]
【发布时间】:2017-07-06 10:31:09
【问题描述】:

您好,我需要为多列按组连接字符串。我知道这个问题的版本已经被问过好几次了(参见Aggregating by unique identifier and concatenating related values into a string),但它们通常涉及连接单个列的值。

我的数据集是这样的:

Sample  group   Gene1   Gene2   Gene3
A       1       a       NA      NA
A       2       b       NA      NA
B       1       NA      c       NA
C       1       a       NA      d
C       2       b       NA      e
C       3       c       NA      NA

我想把它变成每个样本只占用 1 行的格式(组列是可选的):

Sample  group   Gene1   Gene2   Gene3
A       1,2     a,b     NA      NA
B       1       NA      c       NA
C       1,2,3   a,b,c   NA      d,e

由于基因的数量可以达到数千,我不能简单地指定我希望连接的列。 我知道aggregatedplyr 可用于获取组,但我不知道如何为多个列执行此操作。

提前致谢!

编辑

由于我的数据集非常大,包含数千个基因,我意识到 dplyr 太慢了。我一直在试验data.table,下面的代码也能得到我想要的:

setDT(df)[, lapply(.SD, function(x) paste(na.omit(x), collapse = ",")), by = Sample]

现在的输出是:

   Sample group Gene1 Gene2 Gene3
1:      A   1,2   a,b            
2:      B     1           c      
3:      C 1,2,3 a,b,c         d,e

感谢您的帮助!

【问题讨论】:

  • 那些是NAs 还是空字符串("")?
  • 感谢您的澄清。他们是 NAs

标签: r string data.table dplyr concatenation


【解决方案1】:

为此,有summarise_allsummarise_atsummarise_if 函数。使用summarise_all

df %>%
  group_by(Sample) %>%
  summarise_all(funs(paste(na.omit(.), collapse = ",")))
# A tibble: 3 × 5
  Sample group Gene1 Gene2 Gene3
   <chr> <chr> <chr> <chr> <chr>
1      A   1,2   a,b            
2      B     1           c      
3      C 1,2,3 a,b,c         d,e

【讨论】:

  • 感谢两位的回答!但是我的数据集非常大,dplyr 需要很长时间才能运行。我意识到我的问题也可以使用 data.table:stackoverflow.com/a/26981425/6782374 来解决。但是我不知道如何省略 NA。
  • 我已经找到了一种方法并编辑了我的问题以反映我最终使用的代码。感谢您的帮助!
【解决方案2】:

使用dplyr,你可以试试:

dft %>%
  group_by(Sample) %>%
  summarise_each(funs( toString(unique(.))))

给出:

# A tibble: 3 × 5
  Sample   group   Gene1 Gene2    Gene3
   <chr>   <chr>   <chr> <chr>    <chr>
1      A    1, 2    a, b    NA       NA
2      B       1      NA     c       NA
3      C 1, 2, 3 a, b, c    NA d, e, NA

编辑: @Axeman 有正确的想法,使用 na.omit(.) 摆脱空值

【讨论】:

  • summarise_each 将被弃用。
猜你喜欢
  • 2022-01-04
  • 2015-04-29
  • 2021-06-09
  • 2014-02-08
  • 2015-05-15
  • 2013-06-28
相关资源
最近更新 更多