计算每行 R 条件的实例数

Counting number of instances of a condition per row R

我有一个大文件,第一列是 ID,其余 1304 列是基因型,如下所示。

rsID    sample1    sample2    sample3...sample1304
abcd    aa         bb         nc        nc
efgh    nc         nc         nc        nc 
ijkl    aa         ab         aa        nc 

我想计算每行 "nc" 值的数量并将结果输出到另一列,以便我得到以下内容:

rsID    sample1    sample2    sample3...sample1304    no_calls
abcd    aa         bb         nc        nc            2
efgh    nc         nc         nc        nc            4
ijkl    aa         ab         aa        nc            1

table 函数计算每列而非行的频率,如果我转置要在 table 函数中使用的数据,我需要文件如下所示:

abcd         aa[sample1]
abcd         bb[sample2]
abcd         nc[sample3] ...
abcd         nc[sample1304]
efgh         nc[sample1]
efgh         nc[sample2]
efgh         nc[sample3] ...
efgh         nc[sample1304]

使用这种格式,我会得到我想要的以下内容:

ID    nc   aa   ab   bb
abcd  2    1    0    1
efgh  4    0    0    0

有人知道按行获取频率的简单方法吗?我现在正在尝试这个,但是 运行:

需要相当长的时间
rsids$Number_of_no_calls <- apply(rsids, 1, function(x) sum(x=="NC"))

您可以使用 rowSums

df$no_calls <- rowSums(df == "nc")
df
#  rsID sample1 sample2 sample3 sample1304 no_calls
#1 abcd      aa      bb      nc         nc        2
#2 efgh      nc      nc      nc         nc        4
#3 ijkl      aa      ab      aa         nc        1

或者,如 MrFlick 所指出的,要从行总和中排除第一列,您可以稍微修改方法

df$no_calls <- rowSums(df[-1] == "nc")

关于行名:不计入rowSums,你可以做一个简单的测试来证明:

rownames(df)[1] <- "nc"  # name first row "nc"
rowSums(df == "nc")      # compute the row sums
#nc  2  3             
# 2  4  1        # still the same in first row