Filling data frame with previous row value

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

    Perhaps you can make use of na.locf from the "zoo" package after setting values of "0" to NA. Assuming your data.frame is called "mydf":

    mydf$state <- mydf$temp
    mydf$state[mydf$state == 0] <- NA
    
    library(zoo)
    mydf$state <- na.locf(mydf$state)
    #      random temp state
    # 1 0.5024234  1.0   1.0
    # 2 0.6875941  0.0   1.0
    # 3 0.7418837  0.0   1.0
    # 4 0.4453640  0.0   1.0
    # 5 0.5062614  0.5   0.5
    # 6 0.5163650  0.0   0.5
    

    If there were NA values in your original data.frame in the "temp" column, and you wanted to keep them as NA in the newly generated "state" column too, that's easy to take care of. Just add one more line to reintroduce the NA values:

    mydf$state[is.na(mydf$temp)] <- NA
    

提交回复
热议问题