Reputation: 239
So I have a dataframe
mydf
Pro1 Pro2 Pro3 Pro4
Pathway1 Woot <NA> Yeet Yike
Pathway2 Dang <NA> <NA> Yike
Pathway3 Blah Try <NA> Lost
And I wan't to compress the NA's so it looks like this
revisedmydf
Pro1 Pro2 Pro3 Pro4
Pathway1 Woot Yeet Yike
Pathway2 Dang Yike
Pathway3 Blah Try Lost
Basically, the NA's are deleted and then the information in the column next to it is pulled into it's space. I have no idea how to approach this and am not sure if I titled this question correctly or am using the correct terminology. So, if this is a duplicate question out there, I apologize.
Best!
Upvotes: 4
Views: 81
Reputation: 887951
We can use apply
to loop over the rows, concatenate the elements of row that are non-NA along with replicated blanks (""
) based on the number of 'NA' elements (It may be better to have NA instead of ""
- In that case c(x[!is.na(x)], x[is.na(x)])
)
mydf[] <- t(apply(mydf, 1, function(x) c(x[!is.na(x)], rep("", sum(is.na(x))))))
mydf
# Pro1 Pro2 Pro3 Pro4
#Pathway1 Woot Yeet Yike
#Pathway2 Dang Yike
#Pathway3 Blah Try Lost
Or use order
mydf[] <- t(apply(mydf, 1, function(x) x[order(is.na(x))]))
Upvotes: 4