correlation for multtple rows
1
1
Entering edit mode
7.9 years ago
biotechdiya ▴ 30

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 • 14k views
3
Entering edit mode
7.9 years ago
5utr ▴ 370

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,]))

0
Entering edit mode

Thank you Gian. It worked..