如何计算R中每一行的字符串的频率

How to count the frequency of a string for each row in R

我有一个看起来像这样的 .txt 文件:

rs1 NC AB NC     
rs2 AB NC AA  
rs3 NC NC NC  
...  

对于每一行,我想计算 "NC" 的频率,这样我的输出将如下所示:

rs1 2  
rs2 1  
rs3 3  
...

谁能告诉我如何在 R 或 Linux 中执行此操作?非常感谢!

dat <- read.table(text="rs1 NC AB NC rs2 AB NC AA rs3 NC NC NC")
dat <- rbind(dat, dat, dat, dat)

您可以使用逐行 table 来获取每行的频率 在这种情况下,第 1 行到第 4 行的频率等于我复制数据时的频率

freq <- apply(dat, 1, table)
    1 2 3 4 # row-number
AA  1 1 1 1
AB  2 2 2 2
NC  6 6 6 6
rs1 1 1 1 1
rs2 1 1 1 1
rs3 1 1 1 1

如果您想对所有行进行聚合频率,请使用

rowSums(freq)
AA  AB  NC rs1 rs2 rs3 
 4   8  24   4   4   4 
df$count <- rowSums(df[-1] == "NC")
#    V1 V2 V3 V4 count
# 1 rs1 NC AB NC     2
# 2 rs2 AB NC AA     1
# 3 rs3 NC NC NC     3

我们可以在从这个表达式 df[-1] == "NC".

创建的矩阵上使用 rowSums

使用较新版本的 dplyr (>=1.0),您可以使用 rowwisec_across 对列求和。

dat <- read.table(text="
SNP G1 G2 G3
rs1 NC AB NC
rs2 AB NC AA
rs3 NC NC NC", header=TRUE)

library(dplyr)
dat %>% 
  rowwise() %>% 
  mutate(Total = sum(c_across(G1:G3)=="NC"))
#   SNP   G1    G2    G3    Total
#   <chr> <chr> <chr> <chr> <int>
# 1 rs1   NC    AB    NC        2
# 2 rs2   AB    NC    AA        1
# 3 rs3   NC    NC    NC        3