假设我们有一个数据框,其中包含一组3个因变量和6个由分组变量标记的独立变量。使用以下示例代码生成此格式的示例:
false
如果我想在x1到x6的集合上回归y1,y2,y3中的每一个,我可以使用以下内容:
library(tidyverse)
library(broom)
n <- 15
df <- data.frame(groupingvar= sample(letters[1:2], size = n, replace = TRUE),
y1 = rnorm(n,10,1), y2=rnorm(n,100,10), y3=rnorm(n,1000,100),
x1= rnorm(n,10,1), x2=rnorm(n,10,1), x3=rnorm(n,10,1),
x4=rnorm(n,10,1), x5=rnorm(n,10,1), x6=rnorm(n,10,1))
df <- arrange(df,groupingvar)
(通过使用lm()帮助中的以下行:“如果响应是矩阵,则线性模型通过最小二乘法分别拟合到矩阵的每一列。”)
但是,如果我需要首先按分组变量分组然后应用lm函数,那么我不太清楚如何做到这一点。我尝试了以下内容,但它为两个组生成了相同的系数集。
y <- as.matrix(select(df,y1:y3))
x <- as.matrix(select(df,x1:x6))
regs <-lm(y~x)
coeffs <- tidy(regs)
coeffs <- arrange(coeffs,response, term)
答案 0 :(得分:1)
在data.table
中,您可以melt
(重新整形 - 将结果变量堆叠在一列而不是存储在三列中)&amp; lm
groupingvar
和结果变量{/ 1>}:{/ 1>
library(data.table)
setDT(df)
#alternatively, set id.vars = c('groupingvar', paste0('x', 1:6)), etc.
longDT = melt(df, id.vars = grep('y', names(df), invert = TRUE))
#this helper function basically splits a named vector into
# its two components
coefsplit = function(reg) {
beta = coef(reg)
list(var = names(beta), coef = beta)
}
#I personally wouldn't assign longDT, I'd just chain this onto
# the output of melt;
longDT[ , coefsplit(lm(value ~ ., data = .SD)), by = .(groupingvar, variable)]
# groupingvar variable var coef
# 1: a y1 (Intercept) -3.595564e+03
# 2: a y1 x1 -3.796627e+01
# 3: a y1 x2 -1.557268e+02
# 4: a y1 x3 2.862738e+02
# 5: a y1 x4 1.579548e+02
# ...
# 38: b y3 x2 2.136253e+01
# 39: b y3 x3 -3.810176e+01
# 40: b y3 x4 4.187719e+01
# 41: b y3 x5 -2.586184e+02
# 42: b y3 x6 1.181879e+02
# groupingvar variable var coef
答案 1 :(得分:0)
我还找到了一种使用cbind()实现此目的的方法,如下所示:
library(tidyverse)
library(broom)
n <- 20
df4 <- data.frame(groupingvar= sample(1:2, size = n, replace = TRUE),
y1 = rnorm(n,10,1), y2=rnorm(n,100,10), y3=rnorm(n,1000,100),
x1= rnorm(n,10,1), x2=rnorm(n,10,1), x3=rnorm(n,10,1),
x4=rnorm(n,10,1), x5=rnorm(n,10,1), x6=rnorm(n,10,1))
df4 <- arrange(df4,groupingvar)
regs <- df4 %>% group_by(groupingvar) %>%
do(fit = lm(cbind(y1,y2,y3) ~ . -groupingvar, data = .))
coeffs <- tidy(regs, fit)