Reputation: 15
I have 4 large matrixes of the same size A, B, C and D . Each matrix has n samples (columns) and n observations (rows).
A <- structure(list(S1 = c(0L, 0L, 1L, 1L), S2 = c(0L, 1L, 0L, 0L), S3 = c(0L, 0L, 0L, 1L)), class = "data.frame", row.names = c("Ob1", "Ob2", "Ob3", "Ob4"))
# S1 S2 S3
# Ob1 0 0 0
# Ob2 0 1 0
# Ob3 1 0 0
# Ob4 1 0 1
B <- structure(list(S1 = c(0L, 1L, 1L, 1L), S2 = c(0L, 8L, 0L, 0L), S3 = c(0L, 0L, 0L, 1L)), class = "data.frame", row.names = c("Ob1", "Ob2", "Ob3", "Ob4"))
# S1 S2 S3
# Ob1 0 0 0
# Ob2 1 8 0
# Ob3 1 0 0
# Ob4 1 0 1
C <- structure(list(S1 = c(0L, 0L, 4L, 1L), S2 = c(2L, 1L, 0L, 2L), S3 = c(0L, 0L, 0L, 1L)), class = "data.frame", row.names = c("Ob1", "Ob2", "Ob3", "Ob4"))
# S1 S2 S3
# Ob1 0 2 0
# Ob2 0 1 0
# Ob3 4 0 0
# Ob4 1 2 1
D <- structure(list(S1 = c(0L, 0L, 4L, 1L), S2 = c(8L, 1L, 5L, 0L), S3 = c(0L, 0L, 0L, 1L)), class = "data.frame", row.names = c("Ob1", "Ob2", "Ob3", "Ob4"))
# S1 S2 S3
# Ob1 0 8 0
# Ob2 0 1 0
# Ob3 4 5 0
# Ob4 1 0 1
Each matrix contains a different variable. I want to perform a linear regression of 4 variables for each sample and observation of the matrixes. I don't want a linear regression betweeen any combinaton of samples and observations, just pairwise regressions in the form of column 1 and row 1 in matrx A is going to be fitted with column 1 and row 1 in matrixes B, C and D; column 2 and row 2 with column 2 and row 2, and so on.
lm model:
lm(A ~ B * C + D)
I want:
lm(A$S1_Obs1 ~ B$S1_Obs1 * C$S1_Obs1 + D$S1_Obs1)
lm(A$S1_Obs2 ~ B$S1_Obs2 * C$S1_Obs2 + D$S1_Obs2)
lm(A$S1_Obs3 ~ B$S1_Obs3 * C$S1_Obs3 + D$S1_Obs3)
lm(A$S2_Obs1 ~ B$S2_Obs1 * C$S2_Obs1 + D$S2_Obs1)
lm(A$S2_Obs2 ~ B$S2_Obs2 * C$S2_Obs2 + D$S2_Obs2)
lm(A$S2_Obs3 ~ B$S2_Obs3 * C$S2_Obs3 + D$S2_Obs3)
...
Any help appreciated.
Upvotes: 1
Views: 701
Reputation: 2636
Here is an approach using the purrr
package that assigns names as well:
library(purrr)
seq_along(A) %>%
map(~ lm(A[.] ~ B[.] * C[.] + D[.])) %>%
set_names(map(seq_along(.),
~ arrayInd(.x, dim(A)) %>%
paste(collapse = "_")))
Upvotes: 0
Reputation: 887831
We may use asplit
to split by row and then construct the linear model by looping each of the split elements in Map
out <- Map(function(a, b, c, d) lm(a ~ b * c + d),
asplit(A, 1), asplit(B, 1), asplit(C, 1), asplit(D, 1))
Upvotes: 2