Condensation series with NA in Dataframe (R)

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'm not going to compress NA, so it looks like

revisedmydf

            Pro1    Pro2    Pro3    Pro4
Pathway1    Woot    Yeet    Yike
Pathway2    Dang    Yike
Pathway3    Blah    Try     Lost

In principle, the NA is deleted, and then the information in the column next to it is pulled into this space. I have no idea how to approach this and am not sure if I have correctly named this question or use the correct terminology. So, if this is a duplicate question, I apologize.
Best!

+4
source share
1 answer

apply , , NA (""), "NA" ( , NA "" - 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     

order

mydf[] <- t(apply(mydf, 1, function(x) x[order(is.na(x))]))
+4

Source: https://habr.com/ru/post/1682437/


All Articles