`Summary` 多个 LM 和 GLM 对象
`Summary` multiple LM and GLM objects
我在 R 中有 50 个 lm
和 glm
对象。我想获得所有对象的摘要,而不必键入 summary(lm...)
50 次。有快速的方法吗?数据集的名称以相同的方式开头:lin.mod.t# 或 lin.mod.s# 其中 {# = 1,2 ,...,25}。我可以使用
列出所有模型
ls(pattern = "lin.mod")
objects(pattern = "lin.mod")
但我不能运行 summary
使用 ls
或 objects
的结果。我使用了 summary(eval(parse(text = ls(pattern = "lin.mod"))))
,但这只是第一个 运行。有什么建议么?也许使用 lapply
?
这个怎么样?
# 2 sample models
lin.mod.1 <- lm(mpg ~ wt, data = mtcars);
lin.mod.2 <- lm(mpg ~ wt, data = mtcars);
# Get models and store in list
lst <- lapply(ls(pattern = "lin.mod"), get);
# Summary of models
res <- lapply(lst, summary);
解释:get
当前环境中匹配模式 "lin.mod"
并存储在列表 lst
中的所有模型。使用 lapply
存储列表 res
.
中所有模型的 summary
您可以选择 NSE 版本的 BaseR 来解决这个问题,如下所示,我使用了两个函数,eval
和 as.name
,您可以选择 as.symbol 而不是 as.name,因为它们的行为相似:
?as.name
as.name first coerces its argument internally to a character vector
(so methods for as.character are not used). It then takes the first
element and provided it is not ""returns a symbol of that name (and if the element is NA_character_, the name is NA
).
?eval
eval evaluates the expr argument in the environment specified by envir
and returns the computed value. If envir is not specified, then the
default is parent.frame() (the environment where the call to eval was
made).
lin.mod.1 <- lm(mpg ~ wt, data = mtcars)
lin.mod.2 <- lm(mpg ~ hp, data = mtcars)
lin.mod.3 <- lm(mpg ~ disp, data = mtcars)
objects_lms <- ls(pattern ="lin\.mod")
vals <- lapply(objects_lms, function(x)eval(as.name(x)))
lapply(vals, summary)
我在 R 中有 50 个 lm
和 glm
对象。我想获得所有对象的摘要,而不必键入 summary(lm...)
50 次。有快速的方法吗?数据集的名称以相同的方式开头:lin.mod.t# 或 lin.mod.s# 其中 {# = 1,2 ,...,25}。我可以使用
ls(pattern = "lin.mod")
objects(pattern = "lin.mod")
但我不能运行 summary
使用 ls
或 objects
的结果。我使用了 summary(eval(parse(text = ls(pattern = "lin.mod"))))
,但这只是第一个 运行。有什么建议么?也许使用 lapply
?
这个怎么样?
# 2 sample models
lin.mod.1 <- lm(mpg ~ wt, data = mtcars);
lin.mod.2 <- lm(mpg ~ wt, data = mtcars);
# Get models and store in list
lst <- lapply(ls(pattern = "lin.mod"), get);
# Summary of models
res <- lapply(lst, summary);
解释:get
当前环境中匹配模式 "lin.mod"
并存储在列表 lst
中的所有模型。使用 lapply
存储列表 res
.
summary
您可以选择 NSE 版本的 BaseR 来解决这个问题,如下所示,我使用了两个函数,eval
和 as.name
,您可以选择 as.symbol 而不是 as.name,因为它们的行为相似:
?as.name
as.name first coerces its argument internally to a character vector (so methods for as.character are not used). It then takes the first element and provided it is not ""returns a symbol of that name (and if the element is NA_character_, the name is
NA
).
?eval
eval evaluates the expr argument in the environment specified by envir and returns the computed value. If envir is not specified, then the default is parent.frame() (the environment where the call to eval was made).
lin.mod.1 <- lm(mpg ~ wt, data = mtcars)
lin.mod.2 <- lm(mpg ~ hp, data = mtcars)
lin.mod.3 <- lm(mpg ~ disp, data = mtcars)
objects_lms <- ls(pattern ="lin\.mod")
vals <- lapply(objects_lms, function(x)eval(as.name(x)))
lapply(vals, summary)