I have two matrices:
first.matrix = matrix(c(1,1,2,3,3,2,4,1), nrow=2)
second.matrix = matrix(c(2,2,3,3,1,1,4,1), nrow=2)
and I want to find the correlation between the rows in 'first.matrix' and the rows in second.matrix. In Java, I would write something like this:
results <- data.frame("first"=c(1:4),"second"=c(1:4), "cor"=c(1:4))
counter <- 1
for(i in 1:2) {
a <- c(t(first.matrix[i,]))
for(j in 1:2) {
b <- c(t(second.matrix[j,]))
results$cor[counter] <- cor(a,b)
results$first[counter] <- i
results$second[counter] <- j
counter=counter+1
}
}
I'm trying to teach myself to code in R in the "right" way, and have spent time reading R-tutorials and questions here on Stack Overflow. So I know my solution requires the use of apply, but try as I can, I don't understand how to actually write it. All the examples I see are pretty simple and involve finding the sum or the mean of a column or row. The trouble is:
a. I need an 'apply' that can accommodate a function that receives two variables, a row from each matrix. This requires a little manipulation to retrieve the rows. I can solve this with:
c(t(first.matrix[i,]))
but I don't know how to insert that to the 'apply'
b. I need results the tell me what row from the first matrix was compared with what row in the second matrix, and what the result is. In my example, running the code I wrote will result in:
first second cor
1 1 1 0.4000000
2 1 2 -0.6741999
3 2 1 -0.1348400
4 2 2 0.6363636
I don't care if the columns have names or not.
Any solution, hint, or reference will be really appreciated :-)