This is a test version of Biostars. For the public version, visit https://www.biostars.org.
correlation for multtple rows

Hi,

I am trying to write a r code to calculate the pearson correlation for the first row vs the rest of the rows. (1vs2, 1vs3,1vs4,1vs5 so on). I am not sure if apply,lapply or sapply will work for this. Also when I try to loop it says x and y must be of same length, but here always my x is going to row 1 and y is 2:19725.

How can make it workable in R

Thanks,

r

1 answer

R function cor() automatically calculates the correlation between the columns of matrix, so you can transpose your matrix and calculate it like this:

# Creates a random matrix with 5 rows and 6 columns
mat=matrix(rnorm(30),5,6)
# Computes the correlation between the first row and the other 4
cor(mat[1,],t(mat[2:5,]))

Log in to answer this question.