[英]Apply a function to objects in my global environment R
This code chunk creates a 10 objects based of length of alpha.这个代码块基于 alpha 的长度创建了 10 个对象。
alpha <- seq(.1,1,by=.1)
for (i in 1:length(alpha)){
assign(paste0("list_ts_ses_tune", i),NULL)
}
How do I put each function into the new list_ts_ses_tune1 ... null objects I've created?如何将每个函数放入我创建的新 list_ts_ses_tune1 ... null 对象中? Each function puts in a list, and works if I set list_ts_ses_tune1 <- lapply ...每个函数都放在一个列表中,如果我设置 list_ts_ses_tune1 <- lapply ...
for (i in 1:length(alpha))
{
list_ts_ses_tune[i] <- lapply(list_ts, function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i])))
list_ts_ses_tune[i] <- lapply(list_ts_ses_tune[i], "[", c("mean"))
}
Maybe this is a better way to do this?也许这是一个更好的方法来做到这一点? I need each individual output in a list of values.我需要值列表中的每个单独输出。
Edit:编辑:
for (i in 1:length(alpha))
{
list_ts_ses_tune[[i]] <- lapply(list_ts[1:(length(list_ts)/2)],
function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i])))
list_ts_ses_tune[[i]] <- lapply(list_ts_ses_tune[[i]], "[", c("mean"))
}
We can use mget
to return all the objects into a list
我们可以使用mget
将所有对象返回到一个list
mget(ls(pattern = '^list_ts_ses_tune\\d+'))
Also, the NULL list
can be created more easily instead of 10 objects in the global environment此外,可以更轻松地创建 NULL list
而不是全局环境中的 10 个对象
list_ts_ses_tune <- vector('list', length(alpha))
Now, we can just use the OP's code现在,我们可以使用 OP 的代码
for (i in 1:length(alpha))
{
list_ts_ses_tune[[i]] <- lapply(list_ts, function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i])))
}
If we want to create a single data.frame如果我们想创建单个 data.frame
for(i in seq_along(alpha)) {
list_ts_ses_tune[[i]] <- data.frame(Mean = do.call(rbind, lapply(list_ts, function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i]))$mean)))
}
You could simply accomplish everything by doing:您可以通过执行以下操作简单地完成所有操作:
library(forecast)
list_ts_ses_tune <- Map(function(x)
lapply(alpha, function(y)forecast(ses(x,h=24,alpha=y))['mean']), list_ts)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.