Reputation: 3
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
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
Reputation: 388992
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.
Upvotes: 3