Shifting non-NA cells to the left

前端 未结 5 498
走了就别回头了
走了就别回头了 2020-11-27 21:17

There are many NA\'s in my dataset and I need to shift all those cells (at row level) to the left.

Example- my dataframe:

    df=data.frame(x=c(\"         


        
5条回答
  •  生来不讨喜
    2020-11-27 21:52

    You can use the standard apply function:

    df=data.frame(x=c("l","m",NA,NA,"p"),y=c(NA,"b","c",NA,NA),z=c("u",NA,"w","x","y"))
    df2 = as.data.frame(t(apply(df,1, function(x) { return(c(x[!is.na(x)],x[is.na(x)]) )} )))
    colnames(df2) = colnames(df)
    
    > df
         x    y    z
    1    l     u
    2    m    b 
    3     c    w
    4      x
    5    p     y
    > df2
      x    y    z
    1 l    u 
    2 m    b 
    3 c    w 
    4 x  
    5 p    y 
    

提交回复
热议问题