我可以使用rapply
深入查看列表(其结构未知;可能是嵌套的,也可能不是)来提取某些信息?例如,我有一个模型对象列表,其中一个元素也是模型对象列表。我可以一次运行一个函数吗?
df <- data.frame(matrix(rnorm(50), nrow = 10))
names(df) <- c("X","Y1","Y2","Y3","Y4")
modlist <- list(
m1 = lm(Y1 ~ X, data = df),
m2 = lm(Y2 ~ X, data = df),
m3 = list(
m3.1 = lm(Y3 ~ X, data = df),
m3.2 = lm(Y4 ~ X, data = df)
)
)
从每个关系中提取截距:
getcoef <- function(x) coefficients(x)[1]
getcoef(modlist[[1]])
# works fine
rapply(modlist, getcoef, classes = "lm", how = "replace")
# returns unlisted model objects!???
答案 0 :(得分:4)
只需重新定义getcoef
功能并使用lapply
:
> getcoef <- function(x) if(inherits(x, "lm")) coefficients(x)[1] else lapply(x, getcoef)
> str(lapply(modlist, getcoef))
List of 3
$ m1: Named num -0.143
..- attr(*, "names")= chr "(Intercept)"
$ m2: Named num -0.11
..- attr(*, "names")= chr "(Intercept)"
$ m3:List of 2
..$ m3.1: Named num 0.0743
.. ..- attr(*, "names")= chr "(Intercept)"
..$ m3.2: Named num -0.577
.. ..- attr(*, "names")= chr "(Intercept)"
答案 1 :(得分:1)
您可以使用lapply
和递归函数:
recSummary <- function(x, ...){
if("lm" %in% class(x)){
summary(x, ...)
}else{
lapply(x, recSummary, ...)
}
}
lapply(modlist, recSummary)
rapply
似乎在summary
how = replace
的结果
更新: 提出您的修正问题:
getcoef <- function(x) coefficients(x)[1]
recSummary <- function(x, func = summary, ...){
if("lm" %in% class(x)){
func(x, ...)
}else{
lapply(x, recSummary, func, ...)
}
}
lapply(modlist, recSummary, func = getcoef)
$m1
(Intercept)
0.1913376
$m2
(Intercept)
-0.3930023
$m3
$m3$m3.1
(Intercept)
0.1184415
$m3$m3.2
(Intercept)
0.01367811
答案 2 :(得分:0)
这将为您提供所需的信息。我可以用rapply做,但我得到重复,所以这似乎更简单:
> out2 <- unlist(modlist)
> head(names(out2))
[1] "m1.coefficients.(Intercept)" "m1.coefficients.X"
[3] "m1.residuals.1" "m1.residuals.2"
[5] "m1.residuals.3" "m1.residuals.4"
> out2[ grepl("coefficients\\.\\(Intercept", names(out2)) ]
$`m1.coefficients.(Intercept)`
[1] -0.1408831
$`m2.coefficients.(Intercept)`
[1] -0.01388696
$`m3.m3.1.coefficients.(Intercept)`
[1] 0.310378
$`m3.m3.2.coefficients.(Intercept)`
[1] -0.4699532