[英]R - Linear linear regression with variables in different dataframes
I have 4 large matrixes of the same size A, B, C and D. Each matrix has n samples (columns) and n observations (rows).我有 4 个大小相同的大矩阵 A、B、C 和 D。每个矩阵有 n 个样本(列)和 n 个观察值(行)。
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.我想对每个样本执行 4 个变量的线性回归并观察矩阵。 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;我不想要任何样本和观察值组合之间的线性回归,只是矩阵 A 中第 1 列和第 1 行形式的成对回归将与矩阵 B、C 和 D 中的第 1 列和第 1 行相匹配; column 2 and row 2 with column 2 and row 2, and so on.第 2 列和第 2 行,第 2 列和第 2 行,依此类推。
lm model: 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.任何帮助表示赞赏。
We may use asplit
to split by row and then construct the linear model by looping each of the split elements in Map
我们可以使用asplit
按行拆分,然后通过循环 Map 中的每个拆分元素来构造线性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))
Here is an approach using the purrr
package that assigns names as well:这是一种使用purrr
package 的方法,它也分配名称:
library(purrr)
seq_along(A) %>%
map(~ lm(A[.] ~ B[.] * C[.] + D[.])) %>%
set_names(map(seq_along(.),
~ arrayInd(.x, dim(A)) %>%
paste(collapse = "_")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.