简体   繁体   中英

R - selecting non-empty cells in each row and create new columns

I have been searching a lot to find a solution but could not. I would appreciate any help. I have a dataframe like below:

A B C D

x na na z

x t na na 

na z na x 

y na s  na

and my desired output is:

A1 B1 

x z

x t  

z x 

y s 

Assuming your "na"s are actually NA s and you would have equal number of NA s in each row you want to remove, you could do

data.frame(t(apply(df, 1, function(x) x[!is.na(x)])))

#  X1 X2
#1  x  z
#2  x  t
#3  z  x
#4  y  s

If you have string "na" then

data.frame(t(apply(df, 1, function(x) x[x != "na"])))

should work.

How about creating an operator to make it as readable as possible?

library(dplyr)
`%|%` <- function(x,y) ifelse(is.na(x), y, x)

df %>%
  transmute(A1 = A %|% B %|% C %|% D,
            B1 = D %|% C %|% B %|% A)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM