Speed up the loop operation in R

前端 未结 10 2100
说谎
说谎 2020-11-22 00:04

I have a big performance problem in R. I wrote a function that iterates over a data.frame object. It simply adds a new column to a data.frame and a

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 00:11

    This could be made much faster by skipping the loops by using indexes or nested ifelse() statements.

    idx <- 1:nrow(temp)
    temp[,10] <- idx
    idx1 <- c(FALSE, (temp[-nrow(temp),6] == temp[-1,6]) & (temp[-nrow(temp),3] == temp[-1,3]))
    temp[idx1,10] <- temp[idx1,9] + temp[which(idx1)-1,10] 
    temp[!idx1,10] <- temp[!idx1,9]    
    temp[1,10] <- temp[1,9]
    names(temp)[names(temp) == "V10"] <- "Kumm."
    

提交回复
热议问题