简体   繁体   English

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

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

So I have the following 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

I parse it in the following way: 我用以下方式解析它:

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

I then want to do something with each row. 然后,我想对每一行做些事情。 More specifically convert it to contingency table(2xN matrix) and perform the exact Fisher test. 更具体地说,将其转换为列联表(2xN矩阵)并执行精确的Fisher测试。 I have no problem extracting one row manually and do what I want. 我没有问题手动提取一行并做我想要的。

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

But I wanted to ask how to iterate over rows of the table? 但是我想问一下如何遍历表中的行? So function would output statics for each row. 因此,函数将为每一行输出静态数据。 I've tried apply() function, but it did not work for me. 我试过了apply()函数,但是对我来说不起作用。

You could use apply to generate a list of the Fisher test results: 您可以使用apply生成Fisher测试结果的列表:

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

Then you could access row-specific tests with standard list indexing 然后,您可以使用标准列表索引访问特定于行的测试

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 

If you wanted a vector of p-values for each row instead, you could try: 如果您希望每行都有一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM