简体   繁体   中英

R repeat function and store each iteration as object

I am new to R.

I'm trying to create time series matrices with different frequencies out of a sample. To be more specific I have a matrix of monthly prices from 1870 to 2014 from which I want to creat new matrices with increasing frequencies from 1 month to 120 months. For each price frequency I need R to store a seperate object which can then be used outside the function. The original sample has 1730 rows (price observations) and 8 columns (variables).

So far I have come up with this. The function prints all the matrices with seemingly correct frequencies, however I don't know how to save the matrices in individual objects.

asset_prices<-monthly historical prices

     prices.rep <- function(x)  {
        i <- 1
        repeat {
            prices<-x[seq(1, 1730,i),1:8]
            print(prices)
           i <- i+1
           if(i > 120)
            break
        }
    return(prices)
    }

    results.rep<-prices.rep(asset_prices)
    results.rep #only returns the last iteration of the function

Help is very much appreciated. thanks in advance

Consider this:

prices.rep <- function(x)  {
    prices <- list()
    for(i in 1:12) {
        prices[[i]] <- x[seq(1, 1730, i), 1:8]
        #print(prices)
    }
    return(prices)
}

This will return a list of matrices (assuming your x argument is a matrix).

You can also write it more compactly using lapply :

prices.rep <- function(x)
    lapply(1:12, function(i) x[seq(1, 1730, i), 1:8] )

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