Filling data frame with previous row value

前端 未结 7 612
孤街浪徒
孤街浪徒 2020-12-29 13:02

I have a data frame that has 2 columns.

column1 has random numbers in column2 is a place holding column for what i want column3 to look like

  random         


        
7条回答
  •  借酒劲吻你
    2020-12-29 13:56

    Inspired by the solution of @Ananda Mahto, this is an adaption of the internal code of na.locf that works directly with 0's instead of NAs. Then you don't need the zoo package and you don't need to do the preprocessing of changing the values to NA. Benchmarktests show that this is about 10 times faster than the original version.

    locf.0 <- function(x) {
      L <- x!=0
      idx <- c(0, which(L))[cumsum(L) + 1]
      return(x[idx])
    } 
    mydf$state <- locf.0(mydf$temp)
    

提交回复
热议问题