How to move cells with a value located in the rows to the left in the data frame

I am working on a data framework that is mostly similar to 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 matters in a row of rows to the left. In the end, all cells that have a value must be assembled on the left, and all cells with NA must be assembled on the right.

Finally, the data file 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 this.

Many thanks for your help. (Maybe you could also explain what your code does?)

Ramie

+4
source share
5 answers
yourdata[]<-t(apply(yourdata,1,function(x){
                           c(x[!is.na(x)],x[is.na(x)])}))

: , , -, , NA, NA.

+2

naLast " SOfun " .

matrix, as.data.frame, :

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>

:

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

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>
+2

:

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

nddf = ddf
for(i in 1:nrow(ddf))
 nddf[i,] = sort(ddf[i,], na.last=T)

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

:

rowfn = function(rr){
 rr2 = rr; j=1
 for(i in 1:length(rr))    if(!is.na(rr[i])){ rr2[j] = rr[i] ;  j = j+1 } 
 if(j<(length(rr)+1)) for(k in j:length(rr))   rr2[k] = NA
 rr2
 }

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

nddf = ddf
for(i in 1:nrow(ddf)) nddf[i,] = rowfn(ddf[i,])

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

R. , m, , , , data.frame. order , NA . R , -NA .

v <- m[order(row(m), is.na(m))]
dim(v) <- dim(m)
t(v)
##     [,1] [,2] [,3] [,4]
## [1,] "a"  "b"  "c"  NA  
## [2,] "d"  "e"  NA   NA  
## [3,] "f"  "g"  "h"  "i" 
## [4,] "j"  "k"  "l"  NA  

, , , radix. , (?) 100 000 , :

v2 <- m[sort.list(is.na(m) + (row(m)-1L)*2L + 1L, method="radix")]
+1