Filling data frame with previous row value

前端 未结 7 599
孤街浪徒
孤街浪徒 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 14:02

    Here is an interesting way with the Reduce function.

    temp = c(1,0,0,0,.5,0,0,0,0,0,1,0,0,0,0,0,1,0,0.5,0,0,0,1)
    fill_zero = function(x,y) if(y==0) x else y
    state = Reduce(fill_zero, temp, accumulate=TRUE)
    

    If you're worried about speed, you can try Rcpp.

    library(Rcpp)
    cppFunction('
      NumericVector fill_zeros( NumericVector x ) {
        for( int i=1; i

提交回复
热议问题