【问题标题】:loop through column glmer循环通过列 glmer
【发布时间】:2017-02-20 22:23:53
【问题描述】:

我正在尝试通过遍历我的数据集中包含响应变量 (dat_prob) 的列来运行 glmer。我使用的代码如下,改编自对另一个 stackoverflow 问题 (Looping through columns in R) 研究的代码。

他们的代码:

dat_y<-(dat[,c(2:1130)])
dat_x<-(dat[,c(1)])
models <- list()
#
for(i in names(dat_y)){
      y <- dat_y[i]
     model[[i]] = lm( y~dat_x )
    }

我的代码:

dat_prob<-(probs[,c(108:188)])
dat_age<-(probs[,c(12)]) 
dat_dist<-(probs[,c(20)]) 
fyearcap=(probs[,c(25)]) 
fstation=(probs[,c(22)]) 
fnetnum=(probs[,c(23)]) 
fdepth=(probs[,c(24)]) 

models <- list() 
#
for(i in names(dat_prob)){
  y <- dat_prob[i]
  y2=as.vector(y)
  model[[i]] = glmer( y ~ dat_age * dat_dist + (1|fyearcap) + (1|fstation)+
  (1|fnetnum)+ (1|fdepth),family=binomial,REML=TRUE )
}

我收到此错误,类似于超链接问题中收到的错误:

Error in model.frame.default(drop.unused.levels = TRUE, formula = y ~  :
invalid type (list) for variable 'y'

我已经为此工作了好几个小时,现在无法透过树木看到森林。

感谢任何帮助。

【问题讨论】:

  • 您最好将所有内容放在 data.frame 中并对其进行迭代。或者,您可以提前构造公式(无需对数据进行子集化)并将其传递给 glmer 函数。您可以使用sapplylapply 翻阅公式列表。

标签: r loops glm


【解决方案1】:

y &lt;- dat_prob[i] 使y 成为一个列表(或数据框,等等)。列表是向量 - 试试is.vector(list()),所以即使y2 = as.vector(y) 仍然是一个列表/数据框(即使你不使用它)。

class(as.vector(mtcars[1]))
# [1] "data.frame"

要从数据框中提取数值向量,请使用[[: y &lt;- dat_prob[[i]]

class(mtcars[[1]])
# [1] "numeric"

虽然我同意 Roman 的观点 - 使用公式可能是一种更好的方法。试试这样的:

for(i in names(dat_prob)) {
  my_formula = as.formula(paste(i,
    "~ dat_age * dat_dist + (1|fyearcap) + (1|fstation)+ (1|fnetnum)+ (1|fdepth)"
  ))
  model[[i]] = glmer(my_formula, family = binomial, REML = TRUE)
}

我也很怀疑你在做什么尝试 80 种不同的响应变量,但这不是你的问题......

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多