2

I am trying to keep an assigned object from a function (building a ts function to begin to model a univariate process, simple I know!). I am having trouble finding a method to keep objects in my workspace. It works fine just using a for loop but I would like to parameterize the following:

ts.builder<-function(x,y,z){
  for(i in 9:13){
    assign(paste(x,i,sep="_"),ts(yardstick[1:528,i], freq=24))
    assign(paste(y,i,sep="_"),ts(yardstick[529:552,i], freq=24))
    assign(paste(z,i,sep="_"),ts(yardstick[1:552,i], freq=24))
  }
}

ts.builder("yard.book.training","yard.book.small.valid", "yard.book.valid")

Any pointers? I am thinking it may need a return statement, yet I have not found this to be of use yet.

Murray
  • 23
  • 3
  • 3
    You can specify the environment to `assign`, to be the global environment. But it is generally a bad idea to generate variable names in this way. You should consider using a structure such as a list to contain the data. – Matthew Lundberg Dec 19 '12 at 23:40

1 Answers1

4

Untested (a reproducible example helps a lot):

ts.builder <- function() {
  xd <- list()
  yd <- list()
  zd <- list()

  for (i in 9:13) {
    xd[[i]] <- ts(yardstick[1:528,i], freq=24)
    yd[[i]] <- ts(yardstick[529:552,i], freq=24)
    zd[[i]] <- ts(yardstick[1:552,i], freq=24)
  }
  list(yard.book.training=xd, yard.book.small.valid=yd, yard.book.valid=zd)
}

l <- ts.builder()

Then here are the returned values:

l$yard.book.training[[9]]

etc.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • Thanks Matthew, this is the fourth answer of yours I've used. Where I am getting a mishap is keeping the for loop for use in the function. The 9th-13th variables are the ones needing to be put into ts objects. That way, I can embed an arima function within the code. Any thoughts on rolling over those specific positions in the initial data frame? – Murray Dec 19 '12 at 23:56
  • Ah, I didn't refresh. I will work on this later this evening. Thanks so much – Murray Dec 19 '12 at 23:58
  • 1
    You should give Matthew the checkmark if the answer is effective. – IRTFM Dec 20 '12 at 00:26