How to move cells with a value row-wise to the left in a dataframe [duplicate]

Could also try using length<-

df[] <- t(apply(df, 1, function(x) `length<-`(na.omit(x), length(x))))
df
#    X1 X2   X3   X4
# x1  a  b    c <NA>
# x2  d  e <NA> <NA>
# x3  f  g    h    i
# x4  j  k    l <NA>

Leave a Comment