Shifting non-NA cells to the left

前端 未结 5 493
走了就别回头了
走了就别回头了 2020-11-27 21:17

There are many NA\'s in my dataset and I need to shift all those cells (at row level) to the left.

Example- my dataframe:

    df=data.frame(x=c(\"         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 21:46

    Thanks to @Richard Scriven for good observation

    A) with is.na and order, lapply and rbind for aggregation

    nosort.df<-do.call(rbind,lapply(1:nrow(df),function(x) { z=df[x,][order(is.na(df[x,]))];colnames(z)<-c("x","y","z");return(z) } ))
    
    > nosort.df
      x    y    z
    1 l    u 
    2 m    b 
    3 c    w 
    4 x  
    5 p    y 
    

    B) if sorted rows are required:

    with sort, lapply and rbind

    sort.df<-do.call(rbind,lapply(1:nrow(df),function(x) { z=sort(df[x,],na.last=TRUE);colnames(z)<-c("x","y","z");return(z) } ))
    
    > sort.df
      x    y    z
    1 l    u 
    2 b    m 
    3 c    w 
    4 x  
    5 p    y  
    

提交回复
热议问题