如何对R中的每一行执行操作(apply()?)

How to perform operation on each row in R (apply()?)

所以我有以下 table:

118.00  12.00   25.00   161.00  26.00   2.00    9.00    47.00
76.00   218.00  1.00    21.00   11.00   64.00   0.00    9.00
53.00   124.00  2.00    51.00   86.00   25.00   25.00   0.00    20.00   14.00
212.00  104.00  38.00   46.00

我是这样解析的:

data2 <- read.table('to_r.txt', fill=T)

然后我想对每一行做一些事情。更具体地说,将其转换为偶然性 table(2xN 矩阵) 并执行精确的 Fisher 检验。我没有问题手动提取一行并做我想做的事。

myrow = na.omit(as.numeric(as.vector(data2[4,])))
fisher.test(matrix(myrow, nrow = 2, byrow=TRUE))

但我想问一下如何遍历table的行?因此函数将为每一行输出静态信息。我试过 apply() 函数,但它对我不起作用。

您可以使用 apply 生成 Fisher 测试结果列表:

tests <- apply(data2, 1, function(x) fisher.test(matrix(na.omit(x), nrow=2, byrow=TRUE)))

然后您可以使用标准列表索引访问特定于行的测试

tests[[4]]
#   Fisher's Exact Test for Count Data
# 
# data:  matrix(na.omit(x), nrow = 2, byrow = TRUE)
# p-value = 0.0003517
# alternative hypothesis: true odds ratio is not equal to 1
# 95 percent confidence interval:
#  1.467850 4.151196
# sample estimates:
# odds ratio 
#   2.461669 

如果您想要每行的 p 值向量,您可以尝试:

apply(data2, 1, function(x) fisher.test(matrix(na.omit(x), nrow=2, byrow=TRUE))$p.value)
# [1] 0.5809118696 0.0803221157 0.0113166667 0.0003516986