r合并动物园对象for for循环错误

时间:2013-10-12 22:12:50

标签: r for-loop user-defined-functions 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)

问题:我得到这个代码在循环之外运行任何想法,为什么它在我的用户定义函数中不起作用?

1 个答案:

答案 0 :(得分:1)

如果您想循环遍历ADHR替换

的所有列
 for(i in seq_along(ADHR))

 for (i in 1:ncol(ADHR))