2 つの Zoo オブジェクトをマージしようとするとエラーが発生します。それらは同じインデックスを持っています。エラーを分離する部分的なコードは次のとおりです。
DFE[[i]]<-setNames(merge(DEMHR[,i],ADHR[,i]), c(dimnames(DEMHR)[[2]][i],dimnames(ADHR)[[2]][i]))
以下は私が得るエラーです
Error in merge(DEMHR[, i], ADHR[, i]) :
error in evaluating the argument 'x' in selecting a method for function 'merge': Error in rval[i, j, drop = drop., ...] : subscript out of bounds
疑似データを含む完全なコードは次のとおりです。
# setting up some fake data
set.seed(31)
foo <- function(myHour, myDate){
rlnorm(1, meanlog=0,sdlog=1)*(myHour) + (150*myDate)
}
Hour <- 1:24
Day <-1:1080
dates <-seq(as.Date("2010-01-01"), by = "day", length.out= 1080)
myData <- expand.grid( Day, Hour)
names(myData) <- c("Date","Hour")
myData$Adspend <- apply(myData, 1, function(x) foo(x[2], x[1]))
myData$Date <-dates
myData$Demand <-(rnorm(1,mean = 0, sd=1)+.75*myData$Adspend)
myData$Hour<-as.factor(myData$Hour)
######################################################################################
AddLag <- function(DF,Date,Time,RESP,AD,LAG=9,BestPred=4) {
SplitDat<-split(DF,list(DF[[Time]]))
DFE<-vector("list",length(SplitDat))
DATASETS<-vector("list",length(SplitDat))
LAGDAT<-vector("list",length(SplitDat))
CORS<-vector("list",length(SplitDat))
BESTHR<-vector("list",length(SplitDat))
BEST<-vector("list",length(SplitDat))
Lags<-24-LAG
IndxNm<-LAG+2
ADDATE<-DF[,c(1,2,3)]
RESPDATE<-DF[,c(1,2,4)]
HOURAD<-melt(ADDATE, id=c(Date,Time), measured =c(AD))
HOURAD<- cast(HOURAD,as.formula(paste0("... ~",Time)))
ADHR<-zoo(HOURAD,HOURAD[,1])
HOURRSP<-melt(RESPDATE, id=c(Date,Time), measured =c(RESP))
HOURRSP<- cast(HOURRSP,as.formula(paste0("... ~",Time)))
DEMHR<-zoo(HOURRSP,HOURRSP[,1])
for(i in seq_along(ADHR)) {
DFE[[i]]<-setNames(merge(DEMHR[,i],ADHR[,i]), c(dimnames(DEMHR)[[2]][i],dimnames(ADHR)[[2]][i]))
ifelse(i==1,DATASETS[[i]]<-setNames(merge(DFE[[i]],lag(ADHR[,24:Lags],-1)),c(paste0(dimnames(DEMHR)[[2]][i],".Rsp"),dimnames(ADHR)[[2]][i],dimnames(ADHR)[[2]][24:Lags])),DATASETS[[i]]<-setNames(merge(DFE[[i]],DATASETS[[i-1]][,2:IndxNm]),c(paste(dimnames(DEMHR)[[2]][i],".Rsp"),dimnames(ADHR)[[2]][i],dimnames(DATASETS[[i-1]])[[2]][2:IndxNm])))
LAGDAT[[i]]<-na.omit(DATASETS[[i]])
CORS<-sapply(LAGDAT[[i]],cor,y=LAGDAT[[i]][,1])
mask<-(rank(-abs(CORS))<=BestPred)
BESTHR[[i]]<-LAGDAT[[i]][,mask]
BEST[[i]]<-data.frame(Date=time(BESTHR[[i]]),BESTHR[[i]],check.names=FALSE,row.names=NULL)
}
return(BEST)
}
TheTest<-AddLag(myData,"Date","Hour","Demand","Adspend",9,3)
質問: このコードをループの外で実行するようにしましたが、ユーザー定義関数で機能しない理由はありますか?