简体   繁体   中英

Cycling through a vector whose elements are inputs to another function in R

I need to apply all the combinations of the elements of a vector to a particular function, and use these elements as inputs for this function as well. I would like it to be somewhat fast, but any combination of apply and its different flavors has proved fruitless so far.

In short, I have a time series, and I need to fit an ARIMA model to describe this process. The function arima from the package stats requires a set of inputs, since I do not want to do this manually, a function that could do that for me seems in order.

I have so far tried this:

 library(stats)
 #need a vector to cycle and use as inputs in the function
 nums <- c(0:3)
 #random time series
 x <- rnorm(1000,mean=1,sd=1)
 #attempt 1
 lapply(nums, arima(x, order=c(nums,nums,nums)))
 #attempt 2
 lapply(nums, arima(x))
 #attempt 3
 #create another vector, as to start cycle with 1 rather than 0
 nums2 <- c(1:3)
 lapply(nums2, arima(randomtimeseries, c(nums, nums, nums)))

This has to be done this way as this is to be run as a cron job, so no input to be added by a user in order to simplify the above process.

You need to learn to create anonymous functions. Just to be clear: Those were permutations, not combinations. You may want combinations, though and if so look at expand.grid. The vector and vectorization tags are misleading at least in the way that concept is used to describe R practices. There's not going to be any vectorization in the solution.

Perhaps , depending on the actual goals and whether all of the combinations of the num vector are meaningful (which I consider doubtful):

apply( expand.grid(num,num,num), 1, function(o) arima(x, order=c( x[1],x[2],x[3] ) ) )

This also smacks of failure to carefully consider the data in the model by turning this over to an exhaustive process. Statistical issues are likely to be severe if any inference is anticipated.

This looks like a job for the reval package!

First, generate the parameter sets (see Generating all distinct permutations of a list in R and data.frame rows to a list ):

all <- expand.grid(0:2, 0:2, 0:2, stringsAsFactors = FALSE) 
perms <- all[apply(all, 1, function(x) {length(unique(x)) == 3}),]
orders <- as.list(as.data.frame(t(perms)))
names(orders) = NULL

Then, use evalmany() to apply the function:

library(stats)
x <- rnorm(1000,mean=1,sd=1)

require(reval)    
res = evalmany(arima, order = orders, default.args = list(x = x),
  method="set", collate = FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM