Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting columns when using ddply

Tags:

r

plyr

I'm using ddply and am stuck with the way the output is arranged. This is the code I'm using. As you can see, the final output (timeseries.out) has the original data and predicted data in one column.

data <- data.frame(Product = c(rep("Shampoo",5),rep("Soap",5)),
               TSdata = rnorm(10, 1, 10))

tsfun <-function(y){
  arima.out <- arima(y$TSdata)
  arima.fc <- predict(arima.out, n.ahead=5)
  return (data.frame(c(y$TSdata, arima.fc$pred)))
}

library(plyr)
timeseries.out <- ddply(data, .(Product), tsfun)

What I really want is the original data in one column, and the predicted data in another column with NAs filling in the blank spots.

data.out <-data.frame(Product = timeseries.out[1:10,1],
       Data = c(timeseries.out[1:5,2], rep("NA",5)),
       Forecast = c(rep("NA",5),timeseries.out[6:10,2]))

How can I change the returned value from tsfun so it looks like data.out? I've tried a number of things, but either get errors or the wrong result.

Thanks!

like image 487
obug Avatar asked Mar 07 '26 10:03

obug


1 Answers

By changing the return value I was able to get the output I wanted. Thanks to joran for getting me thinking on the right path.

Simple modification of the return statement so two columns are output instead of one

return (data.frame(y$TSdata, as.numeric(arima.fc$pred)))

Return value modified to fit desired output of two columns with NAs

return (data.frame(c(y$TSdata, rep(NA, length(arima.fc$pred))),
                   c(rep(NA, length(y$TSdata)), arima.fc$pred)))
like image 76
obug Avatar answered Mar 09 '26 23:03

obug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!