Filling data frame with previous row value

前端 未结 7 606
孤街浪徒
孤街浪徒 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:44

    Also, unless I'm overlooking something, this seems to work:

    DF$state2 <- ave(DF$temp, cumsum(DF$temp), FUN = function(x) x[x != 0])
    DF
    #       random temp state state2
    #1  0.50242337  1.0   1.0    1.0
    #2  0.68759406  0.0   1.0    1.0
    #3  0.74188374  0.0   1.0    1.0
    #4  0.44536403  0.0   1.0    1.0
    #5  0.50626137  0.5   0.5    0.5
    #6  0.51636498  0.0   0.5    0.5
    #7  0.80780471  0.0   0.5    0.5
    #8  0.24794844  0.0   0.5    0.5
    #9  0.46573337  0.0   0.5    0.5
    #10 0.10370515  0.0   0.5    0.5
    #11 0.07962587  1.0   1.0    1.0
    #12 0.93892894  0.0   1.0    1.0
    #13 0.67771302  0.0   1.0    1.0
    #14 0.11223162  0.0   1.0    1.0
    #15 0.16590718  0.0   1.0    1.0
    #16 0.83619527  0.0   1.0    1.0
    #17 0.38771300  1.0   1.0    1.0
    #18 0.14773708  0.0   1.0    1.0
    #19 0.43928154  0.5   0.5    0.5
    #20 0.08901350  0.0   0.5    0.5
    #21 0.84174743  0.0   0.5    0.5
    #22 0.93173871  0.0   0.5    0.5
    #23 0.80795517  1.0   1.0    1.0
    

提交回复
热议问题