首页 > 解决方案 > 根据 R 中的多个条件计算字符出现次数

问题描述

我正在尝试根据多个条件计算数据框中多个不同字符串的出现次数。我有以下包含以下信息的数据框(mut.total):

   TYPE Sample    Genotype   Mutagen             Dose
1   DUP CD0001c   N2         MA                  20
2   DEL CD0001d   N2         MA                  20
3   DUP CD0030a   N2         MA                  20
4   DEL CD0035a   N2         Mechlorethamine     20
5   INV CD0035a   N2         Mechlorethamine     20
6   INV CD0035a   N2         Mechlorethamine     20
7   DUP CD0035a   N2         Mechlorethamine     20
8   DEL CD0035a   N2         Mechlorethamine     20
9   DEL CD0035c   N2         Mechlorethamine     20
10  DUP CD0035d   N2         Mechlorethamine     20

我想生成一个数据框,按诱变剂和类型显示突变总数和突变来自的样本数量(请记住,一个样本可能会产生相同类型的多个突变)。我的预期输出示例:

          Mutagen Type N.Mut   N.Sample
1              MA  DEL 1       1
2 Mechlorethamine  DEL 3       2
3              MA  DUP 2       2
4 Mechlorethamine  DUP 2       2
5 Mechlorethamine  INV 2       1

使用聚合我能够按诱变剂和类型生成突变数量,但我无法弄清楚如何添加突变来自的样本数量。

aggregate(x=mut.total$TYPE, by=list(Mutagen = mut.total$Mutagen, Type = mut.total$TYPE),
                         FUN = length)
          Mutagen Type N.Mut
1              MA  DEL 1
2 Mechlorethamine  DEL 3
3              MA  DUP 2
4 Mechlorethamine  DUP 2
5 Mechlorethamine  INV 2

标签: rdataframeconditional-statements

解决方案


这是一个dplyr版本:

library(dplyr)

mut.total %>%
  group_by(Mutagen, TYPE) %>%
  summarise(N.Mut = n(), N.Sample = n_distinct(Sample))

输出

  Mutagen         TYPE  N.Mut N.Sample
  <chr>           <chr> <int>    <int>
1 MA              DEL       1        1
2 MA              DUP       2        2
3 Mechlorethamine DEL       3        2
4 Mechlorethamine DUP       2        2
5 Mechlorethamine INV       2        1

推荐阅读