问题
I have 50 lm
and glm
objects in R. I want to get the summary of all of them without having to type summary(lm...)
50 times. Is there a quick way to do it? The names of the dataset begin the same way: lin.mod.t# or lin.mod.s# where {# = 1,2,...,25}. I can list all the models using
ls(pattern = "lin.mod")
objects(pattern = "lin.mod")
But I cannot run summary
for the outcomes of using ls
or objects
. I used summary(eval(parse(text = ls(pattern = "lin.mod"))))
, but this only runs the first one. Any suggestions? Maybe use lapply
?
回答1:
How about this?
# 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);
Explanation: get
all models that match pattern "lin.mod"
from the current environment and store in list lst
. Use lapply
to store summary
of all models in list res
.
回答2:
You may choose NSE version of BaseR to solve this, like below,I am using two functions, eval
and as.name
, You may choose as.symbol instead of as.name as they both behave similarly:
?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)
来源:https://stackoverflow.com/questions/47733886/summary-multiple-lm-and-glm-objects