【发布时间】:2019-07-24 05:54:59
【问题描述】:
我正在估计许多线性模型,其中两个因子变量之间的交互作用来自大量因子变量作为预测变量。因素的级别数可能不同,手动计算级别数非常耗时。从这些模型中,我试图生成一个数据框,其中包含仅用于交互项的每个系数估计的行。 lm 对象中的系数估计值存储在命名向量中,但我将它们存储在 df 中。
目前,我设计了一个函数来为每个模型生成一个包含这些术语的数据框。我可以这样做,保存结果,然后最终读入并附加/加入数据帧,但我知道这非常缓慢且效率低下。
有没有人知道如何计算模型中的交互项的数量,然后将结果存储在我生成的数据框中以适应结果的数量?
下面是一个最小的工作示例,我在生成数据帧后打印它们。我也可以救他们。
# Generate fake data
a <- as.factor(sample(0:1, 20, replace = TRUE))
b <- as.factor(sample(c("a","b","c","d","e","f"), 20, replace = TRUE))
c <- as.factor(sample(0:10, 20, replace = TRUE))
d <- as.factor(sample(0:12, 20, replace = TRUE))
y <- rnorm(20)
df <- data.frame(y,a,b,c,d)
# The factor variable names are:
vars <- c("a","b","c", "d")
# Loop through all the factors
for (i in 1:(length(vars) - 1)){
for (j in (i+1):length(vars)){
# Generate the right-hand side of the formula using
# the fact that (x+y+z)^2 expands in the lm() formula
# to all main and interaction terms for all two-way
# interactions: (x + y + z + x:y + x:z + z:y)
rhs <- c(vars[i], vars[j]) %>%
paste(., collapse = "+") %>%
paste0("(", ., ")", "^2")
# Generate left-hand side
lhs <- paste0("y", " ~ ")
# Generate the model formula
my_mod <- paste0(lhs, rhs) %>%
formula()
# Fit the model, save coefficients
mod_sum <- lm(my_mod, data = df)
mod_coef <- mod_sum$coefficients
# Identify interaction coefficients by the ":"
# symbol and keep only the interaction terms in a df
int_coefs_df <- mod_coef %>%
names() %>%
grep(":",.) %>%
mod_coef[.] %>%
data.frame(estimate = .)
print(int_coefs_df)
}
}
【问题讨论】:
标签: r data-manipulation