i.b
i.b

Reputation: 337

rcorr function correlation of specific variables but not all against all

I would like to use the functionrcorr to correlate variables of a matrix with variables of another matrix but I dont`t want a correlation matrix with all correlated to all.

example data mtcars:

m1 <- as.matrix(mtcars[,c(1,3)])
m2 <- as.matrix(mtcars[,c(4,6)])
cor <- rcorr(y =m1,x =m2, type = "spearman")
output: hp         wt        mpg       disp
hp    1.0000000  0.7746767 -0.8946646  0.8510426
wt    0.7746767  1.0000000 -0.8864220  0.8977064
mpg  -0.8946646 -0.8864220  1.0000000 -0.9088824
disp  0.8510426  0.8977064 -0.9088824  1.0000000

I dont want this output because I am interested in correlated variables of m1 with variables of m2 and not all against all. How can I do it?

Upvotes: 4

Views: 746

Answers (1)

SAL
SAL

Reputation: 2140

As was mentioned by commenters, the rcorr() function is not flexible as it gives the full correlation matrix. I think you probably interested in this function as it gives a list of correlations, sample size, and the p-values each in a matrix form. However, you could do a trick and access your information in the second step by extracting the requested correlations from the output, i.e, both the correlations and the corresponding p-values as follows:

m1 <- as.matrix(mtcars[,c(1,3)])
m2 <- as.matrix(mtcars[,c(4,6)])

library(Hmisc)
cor <- rcorr(y =m1,x =m2, type = "spearman")


# extract only your correlations of interest
my_cor<-cor$r[c("hp","wt"),c("mpg","disp")]
my_cor
        mpg      disp
hp -0.8946646 0.8510426
wt -0.8864220 0.8977064

#likewise, you could extract the corresponding p-values of your correlations of interest

my_pval<-cor$P[c("hp","wt"),c("mpg","disp")]
my_pval
       mpg         disp
hp 5.085932e-12 6.791336e-10
wt 1.487610e-11 3.346212e-12

you could also do directly on the main output of rcorr() to filter values :

cor$r<-cor$r[c("hp","wt"),c("mpg","disp")]
cor$P<-cor$P[c("hp","wt"),c("mpg","disp")]
cor$n<-cor$n[c("hp","wt"),c("mpg","disp")]

hope it could helps

Upvotes: 2

Related Questions