带变化的for循环的回归 [英] Regression with for-loop with changing variables

查看:49
本文介绍了带变化的for循环的回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环中运行回归,并在每个循环中更改变量名称.与此设置类似,此处

I am trying to run a regression in a loop with variables names changing at each loop. Similar to this setup here

最后,我想将拟合结果保存在列表中.

At the end, I would like to save the fitted results in a list.

我的代码如下:

year <- rep(2014:2015, length.out = 10000)
group <- sample(c(0,1,2,3,4,5,6), replace=TRUE, size=10000)
value <- sample(10000, replace = T)
female <- sample(c(0,1), replace=TRUE, size=10000)
smoker <- sample(c(0,1), replace=TRUE, size=10000)

dta <- data.frame(year = year, group = group, value = value, female=female, smoker = smoker)

pc<- dta[, c("female", "smoker")]
names_pc <- names(pc)

m_fit <- vector("list", length(names_pc))

for (i in seq_along(names_pc)){
  m <- lm(value ~ year + group + group:names_pc[i], data = dta)
  m_fit[[i]] <- m$fit
}

...但是出了点问题.我收到以下错误消息.

... but something is wrong. I get the following error message.

Error in model.frame.default(formula = value ~ year + group + group:names_pc[i],  : 
  invalid type (NULL) for variable 'names_pc[i]'

推荐答案

使用 sprintf / paste0 构造公式:

m_fit <- vector("list", length(names_pc))

for (i in seq_along(names_pc)){
  m <- lm(sprintf('value ~ year + group + group:%s', names_pc[i]), data = dta)
  m_fit[[i]] <- m$fit
}

这篇关于带变化的for循环的回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆