如何避免使用 for 循环将嵌套列表的元素获取到顶层?
How do I avoid using a for-loop to get elements of a nested list to the top level?
我正在尝试将一组线性模型的系数提取到数据框中。如何在不使用 for 循环的情况下提取这些值?
为清楚起见,我示例中的数据是虚拟数据。实际项目为一年中的每一天制作气温模型,然后尝试对这些模型的参数进行建模。目前我只能将每个系数累加到一个单独的变量中,然后将其单独应用于我的数据集:
require(tidyverse)
# making different mpg models from displacement, distinguished by cylinder count
models <- mtcars %>%
nest(-cyl, .key = "cardata") %>%
mutate(mod = map(cardata, ~lm(mpg ~ disp, data = .))) %>%
mutate(coefficients = map(mod, coefficients)) #this only extracts a list of coefficients
# currently using one for-loop to extract each coefficient, looking for a more elegant way...
coef.intercept <- c()
for (i in models$coefficients) {
coef.intercept <- c(coef.intercept,i[1])
}
coef.disp <- c()
for (i in models$coefficients) {
coef.disp <- c(coef.disp,i[2])
}
# putting together the final data frame
models <- models %>%
mutate(coef.intercept) %>%
mutate(coef.disp) %>%
select(cyl, coef.intercept, coef.disp) %>%
as.data.frame()
使用 'map' 我可以提取系数列表,但我不能使用“[”运算符来获取各个列表的特定元素。像
mutate(models, coef.intercept = map(models, coefficients[1]))
不起作用,我得到 "Error: Index 1 must have length 1, not 2"。
我目前无法复制您的示例,但我认为您可以从这里开始并根据您的需要调整此解决方案。
A <- list(a = list(1,"j"), b = list(2, "k") , d = list(3, "m" ) )
sapply(A, `[[`, 1)
我正在尝试将一组线性模型的系数提取到数据框中。如何在不使用 for 循环的情况下提取这些值?
为清楚起见,我示例中的数据是虚拟数据。实际项目为一年中的每一天制作气温模型,然后尝试对这些模型的参数进行建模。目前我只能将每个系数累加到一个单独的变量中,然后将其单独应用于我的数据集:
require(tidyverse)
# making different mpg models from displacement, distinguished by cylinder count
models <- mtcars %>%
nest(-cyl, .key = "cardata") %>%
mutate(mod = map(cardata, ~lm(mpg ~ disp, data = .))) %>%
mutate(coefficients = map(mod, coefficients)) #this only extracts a list of coefficients
# currently using one for-loop to extract each coefficient, looking for a more elegant way...
coef.intercept <- c()
for (i in models$coefficients) {
coef.intercept <- c(coef.intercept,i[1])
}
coef.disp <- c()
for (i in models$coefficients) {
coef.disp <- c(coef.disp,i[2])
}
# putting together the final data frame
models <- models %>%
mutate(coef.intercept) %>%
mutate(coef.disp) %>%
select(cyl, coef.intercept, coef.disp) %>%
as.data.frame()
使用 'map' 我可以提取系数列表,但我不能使用“[”运算符来获取各个列表的特定元素。像
mutate(models, coef.intercept = map(models, coefficients[1]))
不起作用,我得到 "Error: Index 1 must have length 1, not 2"。
我目前无法复制您的示例,但我认为您可以从这里开始并根据您的需要调整此解决方案。
A <- list(a = list(1,"j"), b = list(2, "k") , d = list(3, "m" ) )
sapply(A, `[[`, 1)