R Code Programming: filling missing column values down first and then up on a stacked sorted table

前端 未结 1 544
不思量自难忘°
不思量自难忘° 2021-01-29 06:28

I have a dataframe with 3 columns, but the 3rd column has some missing values which need to be filled in with the following logic.

The desired result is that there are n

相关标签:
1条回答
  • 2021-01-29 07:17

    This is essentially a "last observation carried forward" task

    library(zoo)
    levels(df$part)[1] <- NA
    
    df$part <- with(df,
      ave(part, item, FUN=function(x) {
        x <- na.locf(x,na.rm=FALSE)
        x[is.na(x)] <- na.omit(x)[1]
        x
      })
    )
    
    #   item week part
    #1     A    1    X
    #2     A    2    X
    #3     A    3    X
    #4     A    4    X
    #5     A    5    Y
    #6     A    6    Y
    #7     A    7    Y
    #8     B    1    Z
    #9     B    2    Z
    #10    B    3    Z
    #11    D   10    T
    #12    D   11    T
    #13    D   12    U
    #14    D   13    U
    #15    D   14    U
    
    all.equal(df,df2, check.names=FALSE)
    #[1] TRUE
    
    0 讨论(0)
提交回复
热议问题