3

plyrを学ぶ練習として、RobHyndmanによる最近の投稿のplyrバージョンを試してみました。

library(forecast); library(plyr)
# Hyndman, R. J. (2013, Jan 7). Batch forecasting in R
# Retrieved Jan 8, 2013, from Research Tips: http://robjhyndman.com/researchtips/batch-forecasting/

retail <- read.csv("http://robjhyndman.com/data/ausretail.csv",header=FALSE)
retail <- ts(retail[,-1],f=12,s=1982+3/12)

ns <- ncol(retail)
h <- 24
fcast <- matrix(NA,nrow=h,ncol=ns)
for(i in 1:ns)
  fcast[,i] <- forecast(retail[,i],h=h)$mean

write(t(fcast),file="retailfcasts.csv",sep=",",ncol=ncol(fcast))

しかし、私は苦労しました。これは私の試みです:

n.cols <- ncol(retail)
h <- 24
series.names <- names(retail[,2:n.cols])

fcast.func <- function(retail) {
  retail.ts <- ts(retail,f=12,s=1982+3/12)  
  fcast.func <- forecast(retail.ts,h=h)$mean
}

ddply.fcast <- ddply(.data=retail[,2:n.cols], .variables=series.names, .fun=colwise(fcast.func))

これは値を返しません。誰かが私のプライヤーの誤解を手伝ってくれませんか?

4

1 に答える 1

4

問題はddply(、最初d = datatype of input = data.frameと 2 番目の を使用することですd = datatype of output = data.frame (again)。ただし、提供している入力retail[, 2:ncols]data.frame.

class(retail)
[1] "mts" "ts"

代わりに、を入力としてldply受け取りlist、関数を実行して を出力しようとすることができますdata.frame。この方法で達成できます。

require(forecast)
require(plyr)

retail <- read.csv("http://robjhyndman.com/data/ausretail.csv",header=FALSE)
retail <- ts(retail[,-1],f=12,s=1982+3/12)

ns <- ncol(retail)
h <- 24
plyr.fcast <- t(ldply(1:ns, function(idx) {
    c(forecast(retail[, idx], h = h)$mean)
}))

これにはかなりの時間がかかります。並行して実行したい場合 (多くのコアを持つクラスター/マシンで実行していると仮定して)、パッケージdoMCをインストールしてから、次のように使用できます。

require(doMC)
registerDoMC(20) # BEWARE: use it if you have 20 processors available!!
plyr.fcast <- t(ldply(1:ns, function(idx) {
    c(forecast(retail[, idx], h = h)$mean)
}, .parallel = TRUE))

転置は と等しい結果を与え、またからの出力を a にfcast型キャストします。したがって、同じ構文を使用してファイルに書き込むことができます。data.frameplyrmatrixwrite

お役に立てれば。

于 2013-01-10T13:20:25.937 に答える