Reputation: 89
I have two dataframes:
dataframe1
name1 500
name2 394
name3 344
...
name2000 300
dataframe2
name1 200
name2 194
name3 44
...
name2000 100
And an empty 2000X2000 matrix (empty.matrix
)
What I want is to fill this matrix with correlation values between the two dataframes. So that the first element in df1
will have a correlation value with every element of df2
... up until element 2000
. I am doing this through the following code:
for (i in 1:2000) {
for (j in 1:2000){
empty.matrix[i,j] <- cor(df1$V1[[i]],df2$V2[[j]])
}
}
Problem is, this is taking forever. Anybody have a quicker way of getting this through? Thanks!
Upvotes: 2
Views: 2283
Reputation: 6489
assuming that your data frames have the same number of rows, the following code should work:
cor(dataframe1, dataframe2)
Here is an example using the mtcars
data set in R:
cor(mtcars[1:5], mtcars[6:11])
wt qsec vs am gear carb
mpg -0.8676594 0.41868403 0.6640389 0.5998324 0.4802848 -0.5509251
cyl 0.7824958 -0.59124207 -0.8108118 -0.5226070 -0.4926866 0.5269883
disp 0.8879799 -0.43369788 -0.7104159 -0.5912270 -0.5555692 0.3949769
hp 0.6587479 -0.70822339 -0.7230967 -0.2432043 -0.1257043 0.7498125
drat -0.7124406 0.09120476 0.4402785 0.7127111 0.6996101 -0.090789
Upvotes: 4