rj2700
rj2700

Reputation: 1965

Output multiple objects from function R

I'm not too sure if this question exists already or not. But after looking around the internet, I can't find anything that relates to my specific problem.

So, in R programming, I would like to mass output objects (specifically time series objects) from a data frame by splitting it. Before this, I have been pasting duplicate concatenation commands for each user and it feels like an extremely tedious process, so I was wondering if I could just build a function that will split a data frame by a variable, apply the ts() function, label that object created, and output all objects created.

Now ideally, the first thing I thought of was using the by command and apply a function to each split. For example, below is the code that I tried (note, this is just a small example, my real data frame is much larger than this).

#test df for stackoverflow
df<-data.frame(user=c(rep(1,5),rep(2,5),rep(3,5),rep(4,5)))
df$values<-c(10,20,30,40,9,19,29,39,11,21,31,41,12,22,32,42,8,18,34,44)

#playing around with the by command
dd<-by(df,df$user,FUN=function(x){
  time = ts(x$values,freqency=2),
  label = x$user[1],
  label<-time,
  return(label)
})

The error just says there's an error with the squiggly bracket. I've also looked at ddply in the 'plyr' package, but I couldn't get that working either.

Any advice/help/comments would be greatly appreciated, thanks.

Upvotes: 0

Views: 520

Answers (1)

dickoa
dickoa

Reputation: 18437

If I understood correctly you want to split your data.frame by a variable and transform each portion as a time series object.

You can use plyr and get the result as a list (if your the number of data per user are not equal)

require(plyr)
dlply(df, .(user), function(df) ts(df$value, frequency = 12))

You can still use by if you want too

by(df$value, df$user, function(x) ts(x, frequency = 12))

## df$user: 1
##   Jan Feb Mar Apr May
## 1  10  20  30  40   9
## ------------------------------------------------ 
## df$user: 2
##   Jan Feb Mar Apr May
## 1  19  29  39  11  21
## ------------------------------------------------ 
## df$user: 3
##   Jan Feb Mar Apr May
## 1  31  41  12  22  32
## ------------------------------------------------ 
## df$user: 4
##   Jan Feb Mar Apr May
## 1  42   8  18  34  44

Upvotes: 2

Related Questions