Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

I'm working on a dataframe that basically looks like this one.


   X1   X2   X3 X4
x1  a    b   NA  c
x2  d   NA   NA  e
x3  f    g    h  i
x4  j   NA    k  l

What I want to do is move each cell that has a value row-wise to the left. At the end all cells that have a value should be gathered to the left while all cells with NAs should be gathered to the right.

Finally, the dataframe should look like this:


   X1   X2   X3 X4
x1  a    b   c  NA
x2  d    e   NA NA
x3  f    g    h  i
x4  j    k    l NA

Unfortunately, I have no idea how to do it.

Thank you very much for your help. (Maybe you could also explain what your code is doing?)

Rami

like image 648
Rami Al-Fahham Avatar asked Oct 30 '14 11:10

Rami Al-Fahham


2 Answers

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>
like image 152
David Arenburg Avatar answered Nov 06 '22 09:11

David Arenburg


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")
like image 44
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 06 '22 10:11

A5C1D2H2I1M1N2O1R2T1