【问题标题】:Accessing dynamically created variables in R在 R 中访问动态创建的变量
【发布时间】:2021-08-13 10:56:10
【问题描述】:

我创建了一些线性模型并将它们的参数存储在变量中。我以“动态”方式创建的变量的名称。 现在,虽然创建工作正常,但我现在不知道如何以“动态”方式访问例如参数。这个例子虽然完全没有意义,但应该说明这一点:

q = c(0.01, 0.02)
for(i in seq_along(q)){
  assign(paste0("lm_", q[[i]]), lm(mtcars$mpg ~ mtcars$disp)) 
}

# access the coefficients for each linear model
for(i in seq_along(q)){
  intercept = coef(paste0("lm_", q[[i]]))[[1]] # does not work...
  slope = coef(paste0("lm_", q[[i]]))[[2]] # does not work...
  cat("Write the coefficients to some file...")
}

所以我的问题是如何访问动态创建的线性模型的系数。

【问题讨论】:

  • 使用列表或向量而不是一系列独立变量不是更好吗?在我看来,这将使您的代码更简单、更易于维护,并让您更轻松地访问所需的信息。
  • 这听起来不错!我仍然会对如何做到这一点感兴趣。我想有一些引用,取消引用......涉及,我想更好地理解:)
  • 对于准引用,请提前阅读 R 第 14 章

标签: r dplyr lm rlang quoting


【解决方案1】:

扩展我上面的评论,这就是我如何重新制定上面的(令人愉快的毫无意义的)示例。我已重命名您的 lm_xxxx 变量,因为使用列表,等效变量名称将是 lm_ 或类似名称,这与我喜欢的 lm 函数太相似了。

q <- c(0.01, 0.02)
models <- lapply(
            1:length(q),
            function(x) lm(mtcars$mpg ~ mtcars$disp)
          )
names(models) <- q

intercepts <- lapply(models, function(x) coef(x)[[1]])
intercepts

slopes <- lapply(models, function(x) coef(x)[[2]])
slopes

给予

$`0.01`
[1] 29.59985

$`0.02`
[1] 29.59985

对于intercepts

$`0.01`
[1] -0.04121512

$`0.02`
[1] -0.04121512

slopes

【讨论】:

  • 这确实是清除了!非常感谢
【解决方案2】:

使用get。以下按预期工作

q = c(0.01, 0.02)
for(i in seq_along(q)){
  assign(paste0("lm_", q[[i]]), lm(mtcars$mpg ~ mtcars$disp)) 
}

# access the coefficients for each linear model
for(i in seq_along(q)){
  intercept = coef(get(paste0("lm_", q[[i]])))[[1]] 
  slope = coef(get(paste0("lm_", q[[i]])))[[2]] 
  cat("Write the coefficients to some file...")
}
#> Write the coefficients to some file...Write the coefficients to some file...


#check
intercept
#> [1] 29.59985
slope
#> [1] -0.04121512

reprex package (v2.0.0) 于 2021-05-25 创建

【讨论】: