【问题标题】:frequency count across multiple columns using r使用 r 跨多列的频率计数
【发布时间】:2018-07-23 17:14:48
【问题描述】:

我有一个格式如下的数据框:

x <-
Chrom    sample1    sample2    sample3  ...
Contig12    0/0     0/0     0/1
Contig12    ./.     ./.     0/0
Contig28    0/0     0/0     0/0
Contig28    1/1     1/1     1/1
Contig55    0/0     0/0     0/1
Contig55    0/1     0/1     0/1
Contig61    ./.     0/1     1/1
.
.
.

有 ~20000 行和 ~100 个唯一列,我试图计算每个唯一状态在每列(样本)中出现的次数,以便我得到:

         sample1    sample2     sample3     ...
./.      2          1           0
0/0      3          3           2
0/1      1          2           3
1/1      1          1           2

关于如何做到这一点的任何建议?我曾尝试使用 plyr 包中的 count() ,但我无法弄清楚如何在每一列中使用它。

非常感谢任何帮助!

【问题讨论】:

    标签: r count


    【解决方案1】:
    library(dplyr)
    df %>% gather(key, value, -Chrom) %>% # gather turn dataset from wide to long format by collapse (collect) values in all columns 
                                          #except Chrom into two columns key and value. See ?gather for more info
           dplyr::select(-Chrom) %>%      #select all columns except Chrom i.e. key and value 
           table()                        # count the number of each unique pear
    
             value
     key       ./. 0/0 0/1 1/1
      sample1   2   3   1   1
      sample2   1   3   2   1
      sample3   0   2   3   2
    

    数据

    df <- read.table(text="
          Chrom    sample1    sample2    sample3
                 Contig12    0/0     0/0     0/1
                 Contig12    ./.     ./.     0/0
                 Contig28    0/0     0/0     0/0
                 Contig28    1/1     1/1     1/1
                 Contig55    0/0     0/0     0/1
                 Contig55    0/1     0/1     0/1
                 Contig61    ./.     0/1     1/1
                  ",header=T, stringsAsFactors = F)
    

    【讨论】:

    • @RavinderSingh13 感谢您的好话。请检查我的更新。
    猜你喜欢
    • 2012-06-08
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2016-11-18
    • 2021-05-28
    相关资源
    最近更新 更多