如何将列表中的每个元素作为未命名参数传递给函数? [英] How do I pass every element of a list to a function as unnamed arguments?

查看:84
本文介绍了如何将列表中的每个元素作为未命名参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在列表中存储了一些模型:

Let's say I have some models stored in a list:

mods <- list()
mods[[1]] <- lm(mpg ~ disp, data = mtcars)
mods[[2]] <- lm(mpg ~ disp + factor(cyl), data = mtcars)
mods[[3]] <- lm(mpg ~ disp * factor(cyl), data = mtcars)

我想用stats::AIC比较它们.我正在寻找从AIC(mods[[1]], mods[[2]], mods[[3]])获得的输出,但是我希望将其概括为任意长的列表.我以为

And I want to compare them using stats::AIC. I'm looking for the output I would get from AIC(mods[[1]], mods[[2]], mods[[3]]), but I'd like it to generalize to an arbitrarily long list. I thought that

do.call(AIC, mods)

可以工作,但是它返回的内容非常冗长且无济于事. (如果该列表已命名,除非其中一个名称为object(与AIC的第一个参数相对应),否则将产生错误,但是您将再次获得详细的输出.)

would work, but it returns something that's very verbose and unhelpful. (If the list is named, an error results unless one of the names is object, corresponding the the first argument of AIC, but then you just get the verbose output again.)

do.call失败后,我开始考虑采用eval(parse())解决方案,但我认为应该首先在这里提出问题.

After the failure of do.call, I started thinking about an eval(parse()) solution, but I figured I should ask here first.

推荐答案

summary(do.call(AIC, mods))
       df         AIC       
 Min.   :3   Min.   :153.4  
 1st Qu.:4   1st Qu.:159.6  
 Median :5   Median :165.8  
 Mean   :5   Mean   :163.1  
 3rd Qu.:6   3rd Qu.:168.0  
 Max.   :7   Max.   :170.2  

但这可能不是您想要的.巴蒂斯特有答案:

But this likely isn't what you want. Baptiste has the answer:

my.aic <- function(x) {
  x <- do.call(AIC, x)
  rownames(x) <- NULL
  return(x)
}
my.aic(mods)
##   df      AIC
## 1  3 170.2094
## 2  5 165.7680
## 3  7 153.4352

这很接近:

AIC(mods[[1]], mods[[2]], mods[[3]])
##           df      AIC
## mods[[1]]  3 170.2094
## mods[[2]]  5 165.7680
## mods[[3]]  7 153.4352

这篇关于如何将列表中的每个元素作为未命名参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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