Add missing value in column with value from row above

后端 未结 5 519
夕颜
夕颜 2020-12-30 01:57

Every week I a incomplete dataset for a analysis. That looks like:

df1 <- data.frame(var1 = c(\"a\",\"\",\"\",\"b\",\"\"), 
             var2 = c(\"x\",\"         


        
5条回答
  •  一生所求
    2020-12-30 02:27

    Here is one way of doing it by making use of run-length encoding (rle) and its inverse rle.inverse:

    fillTheBlanks <- function(x, missing=""){
      rle <- rle(as.character(x))
      empty <- which(rle$value==missing)
      rle$values[empty] <- rle$value[empty-1] 
      inverse.rle(rle)
    }
    
    df1$var1 <- fillTheBlanks(df1$var1)
    

    The results:

    df1
    
      var1 var2
    1    a    x
    2    a    y
    3    a    z
    4    b    x
    5    b    z
    

提交回复
热议问题