R:如何编写一个for循环来读取矩阵中的每两行? [英] R: How to write a for loop that reads every two lines in a matrix?

查看:563
本文介绍了R:如何编写一个for循环来读取矩阵中的每两行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用cor.test()计算相关性统计信息.我有一个数据矩阵,其中要测试的两对在连续的行上(我有一千对,因此以后也需要对此进行校正).我当时想我可以遍历矩阵中的每两行和两行并执行测试(即,首先在row1和row2之间进行测试,然后在row3和row4之间,row5和row6等之间进行测试),但是我不知道该怎么做.进行这种循环.

I want to calculate correlation statistics using cor.test(). I have a data matrix where the two pairs to be tested are on consecutive lines (I have more than thousand pairs so I need to correct for that also later). I was thinking that I could loop through every two and two lines in the matrix and perform the test (i.e. first test correlation between row1 and row2, then row3 and row4, row5 and row6 etc.), but I don't know how to make this kind of loop.

这是我在单对上进行测试的方式:

This is how I do the test on a single pair:

d = read.table(file="cor-test-sample-data.txt", header=T, sep="\t", row.names = 1)
d = as.matrix(d)
cor.test(d[1,], d[2,], method = "spearman")

推荐答案

您可以尝试

 res <-  lapply(split(seq_len(nrow(mat1)),(seq_len(nrow(mat1))-1)%/%2 +1),
               function(i){m1 <-  mat1[i,]
                if(NROW(m1)==2){ 
                 cor.test(m1[1,], m1[2,], method="spearman")
                  }
                else NA 
         })

要获取p-values

 resP <- sapply(res, function(x) x$p.value)
 indx <- t(`dim<-`(seq_len(nrow(mat1)), c(2, nrow(mat1)/2)))
 names(resP) <- paste(indx[,1], indx[,2], sep="_")
 resP  
 #       1_2        3_4        5_6        7_8       9_10      11_12      13_14 
 #0.89726818 0.45191660 0.14106085 0.82532260 0.54262680 0.25384239 0.89726815 
 #     15_16      17_18      19_20      21_22      23_24      25_26      27_28 
 #0.02270217 0.16840791 0.45563229 0.28533447 0.53088721 0.23453161 0.79235990 
 #    29_30      31_32 
 #0.01345768 0.01611903 

或使用mapply(假设行是偶数)

Or using mapply (assuming that the rows are even)

  ind <- seq(1, nrow(mat1), by=2) #similar to the one used by @CathG in for loop
  mapply(function(i,j) cor.test(mat1[i,], mat1[j,],
                method='spearman')$p.value , ind, ind+1) 

数据

set.seed(25)
mat1 <- matrix(sample(0:100, 20*32, replace=TRUE), ncol=20)    

这篇关于R:如何编写一个for循环来读取矩阵中的每两行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆