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
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>
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With