`Summary` multiple LM and GLM objects

一世执手 提交于 2019-12-13 03:52:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!