将函数应用于 R 中嵌套列表的某些元素
apply a function to some elements of a nested lists in R
我希望仅将函数应用于嵌套列表的某些元素
l <- list()
l$a$forecast <- rnorm(3)
l$a$model <- "arima"
l$b$forecast <- rnorm(3)
l$b$model <- "prophet"
期望的输出是这样的:
将求和函数应用于列表的 $forecast 元素
fcst <- c(sum(l$a$forecast),sum(l$b$forecast))
mdl <- c(l$a$model,l$b$model)
df <- data.frame(fcst,mdl)
我试过这样的事情:
df <- lapply(l$forecast, function(x) sum(x))
df <- do.call(rbind, Map(cbind, sku = names(df)))
您可以使用对象 letters
获取字母,然后在循环中使用其输出:
n = 2 #number of lists you have
sumfore = model = vector()
for(i in letters[seq(1,n,1)]){
sumfore[i] = sum(l[[i]]$forecast)
model[i] =l[[i]]$model}
newdf = data.frame(sumfore, model)
do.call(
rbind,
lapply(
l,
function(x) list(fcst = sum(x$forecast), model = x$model)
)
)
由于您知道返回对象的确切尺寸,因此在这种情况下可以使用 vapply
来稍微提高性能:
vapply(
l,
FUN = function(x) list(fcst = sum(x$forecast), model = x$model),
FUN.VALUE = list(fcst = numeric(1), model = character(1))
)
但是,生成的对象可能很难处理。
在 rrapply
包中使用 rrapply()
并结合 dplyr 的 bind_rows()
的另一种方法。这也扩展到包含更深嵌套级别的列表。
rrapply::rrapply(l, condition = function(x, .xname) .xname == "forecast", f = sum) %>%
dplyr::bind_rows()
#> # A tibble: 2 x 2
#> forecast model
#> <dbl> <chr>
#> 1 -1.28 arima
#> 2 1.10 prophet
数据
set.seed(1)
l <- list(
a = list(forecast = rnorm(3), model = "arima"),
b = list(forecast = rnorm(3), model = "prophet")
)
我希望仅将函数应用于嵌套列表的某些元素
l <- list()
l$a$forecast <- rnorm(3)
l$a$model <- "arima"
l$b$forecast <- rnorm(3)
l$b$model <- "prophet"
期望的输出是这样的: 将求和函数应用于列表的 $forecast 元素
fcst <- c(sum(l$a$forecast),sum(l$b$forecast))
mdl <- c(l$a$model,l$b$model)
df <- data.frame(fcst,mdl)
我试过这样的事情:
df <- lapply(l$forecast, function(x) sum(x))
df <- do.call(rbind, Map(cbind, sku = names(df)))
您可以使用对象 letters
获取字母,然后在循环中使用其输出:
n = 2 #number of lists you have
sumfore = model = vector()
for(i in letters[seq(1,n,1)]){
sumfore[i] = sum(l[[i]]$forecast)
model[i] =l[[i]]$model}
newdf = data.frame(sumfore, model)
do.call(
rbind,
lapply(
l,
function(x) list(fcst = sum(x$forecast), model = x$model)
)
)
由于您知道返回对象的确切尺寸,因此在这种情况下可以使用 vapply
来稍微提高性能:
vapply(
l,
FUN = function(x) list(fcst = sum(x$forecast), model = x$model),
FUN.VALUE = list(fcst = numeric(1), model = character(1))
)
但是,生成的对象可能很难处理。
在 rrapply
包中使用 rrapply()
并结合 dplyr 的 bind_rows()
的另一种方法。这也扩展到包含更深嵌套级别的列表。
rrapply::rrapply(l, condition = function(x, .xname) .xname == "forecast", f = sum) %>%
dplyr::bind_rows()
#> # A tibble: 2 x 2
#> forecast model
#> <dbl> <chr>
#> 1 -1.28 arima
#> 2 1.10 prophet
数据
set.seed(1)
l <- list(
a = list(forecast = rnorm(3), model = "arima"),
b = list(forecast = rnorm(3), model = "prophet")
)