gpt4 book ai didi

r - 我可以在模型对象的嵌套列表上使用 rapply

转载 作者:行者123 更新时间:2023-12-02 09:36:38 26 4
gpt4 key购买 nike

我可以使用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!???

最佳答案

只需重新定义您的 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)"

关于r - 我可以在模型对象的嵌套列表上使用 rapply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25495702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com