mash
mash

Reputation: 3

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 

Upvotes: 0

Views: 4052

Answers (2)

kwiscion
kwiscion

Reputation: 596

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)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388992

Assuming your "na"s are actually NAs and you would have equal number of NAs 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.

Upvotes: 3

Related Questions