Question

Suppose I have three variables viz, x,y and z. Now I want to find the correlation between x and y and also between x and z. I know this is the easy step. But finally I would want the output to be a data frame shown as under:

Desc      Correlation
x and y      .56
x and z      .65

How can it be done using a for loop or some other convenient way? Also in place of 'x and y' I would like the actual variable name to be printed.

Note: I have 28 vars in total, so the data frame will have 28 rows.

Was it helpful?

Solution

set.seed(1)
x <- runif(100); y <- runif(100); z <- runif(100) 
cor <- cor(x, cbind(y, z))
data.frame(Desc=paste("x and", colnames(cor)), 
           Correlation=as.vector(cor))
#      Desc Correlation
# 1 x and y  0.01703215
# 2 x and z  0.14450632
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top