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

Solution 1:

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>

Solution 2:

You can grab my naLast function from my "SOfun" package.

The result would be a matrix, but you can easily wrap it in as.data.frame if you want:

as.data.frame(naLast(mydf, by = "row"))
#    X1 X2   X3   X4
# x1  a  b    c <NA>
# x2  d  e <NA> <NA>
# x3  f  g    h    i
# x4  j  k    l <NA>

Install the package with:

library(devtools)
install_github("mrdwab/SOfun")

Solution 3:

yourdata[]<-t(apply(yourdata,1,function(x){
                           c(x[!is.na(x)],x[is.na(x)])}))

should work : for each row, it replaces the row by a vector that consists of, first, the value that are not NA, then the NA values.