【问题标题】:Looping over objects in R循环遍历 R 中的对象
【发布时间】:2020-01-28 00:31:48
【问题描述】:

我正在尝试遍历 R 中的对象。

myfunc.linear.pred <- function(x){
  linear.pred <- predict(object = x)
  w <- exp(linear.pred)/(1+exp(linear.pred))
  as.vector(w)
}

这里的功能可以正常工作。它返回一个 48 行的向量,它来自对象 x。现在“x”不过是 GLM 函数的完整回归模型(想想:mod.fit &lt;- glm (dep~indep, data = data))。问题是我有 20 个不同的此类('mod.fit')对象,需要为每个对象找到预测。我可以从字面上重复代码,但我正在寻找一个更简洁的解决方案。所以我想要的是一个 48 行 20 列的矩阵,用于上述函数。这对于高级用户来说可能是基本的,但我只对数字使用过“apply”和“for”循环,从不使用对象。我查看了 lapply 但无法弄清楚。

我试过了:(这可能是愚蠢的)

allmodels <- c(mod.fit, mod.fit2, mod.fit3)
lpred.matrix <- matrix(data=NA, nrow=48, ncol=20)
for(i in allmodels){
  lpred.matrix[i,] <- myfunc.linear.pred(i)
}

这显然行不通,因为allmodels 有一个“列表”类,它包含来自 GLM 函数的所有内容。希望有人可以提供帮助。谢谢!

【问题讨论】:

  • 试试sapply(allmodels, myfunc.linear.pred)
  • lpred.matrix中的索引是不是放错地方了?我认为应该是lpred.matrix[,i],因为您正在填写该列。

标签: r


【解决方案1】:

为了使用 lapply,您必须有一个列表对象而不是矢量对象。像这样的东西应该可以工作:

## Load data
data("mtcars")

# fit models
mod.fit1 <- glm (mpg~disp, data = mtcars)
mod.fit2 <- glm (mpg~drat, data = mtcars)
mod.fit3 <- glm (mpg~wt, data = mtcars)

# build function
myfunc.linear.pred <- function(x){
  linear.pred <- predict(object = x)
  w <- exp(linear.pred)/(1+exp(linear.pred))
  as.vector(w)
}

# put models in a list
allmodels <- list("mod1" = mod.fit1, "mod2" = mod.fit2, "mod2" = 
mod.fit3)

# use lapply and do.call to generate matrix of prediction results
df <- do.call('cbind', lapply(allmodels, function(x){
  a <- myfunc.linear.pred(x)
}))

希望对你有帮助

【讨论】:

  • 工作就像一个魅力!谢谢楼主!
猜你喜欢
  • 2023-03-28
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多