Correlation between two dataframes by row

Depending on whether you want a cool or fast solution you can use either

diag(cor(t(df1), t(df2)))

which is cool but wasteful (because it actually computes correlations between all rows which you don't really need so they will be discarded) or

A <- as.matrix(df1)
B <- as.matrix(df2)
sapply(seq.int(dim(A)[1]), function(i) cor(A[i,], B[i,]))

which does only what you want but is a bit more to type.


I found that as.matrix is not required.

Correlations of all pairs of rows between dataframes df1 and df2:

sapply(1:nrow(df1), function(i) cor(df1[i,], df2[i,]))

and columns:

sapply(1:ncol(df1), function(i) cor(df1[,i], df2[,i]))