Search code examples
rdplyrplyrreshapecbind

How to combine columns in a data frame so that they overlap in R?


Basically, I have data from a between subjects study design that looks like this:

>    head(have, 3)
              A    B    C
        1          b 
        2     a  
        3               c

Here, A, B, C are various conditions of the study, so each subject (indicated by each row), only has a value for one of the conditions. I would like to combine these so that it looks like this:

>    head(want, 3)
             all
        1     b 
        2     a  
        3     c

How can I combine the columns so that they "overlap" like this?

So far, I have tried using some of dplyr's join functions, but they haven't worked out for me. I appreciate any guidance in combining my columns in this way.


Solution

  • We can use pmax

    want <- data.frame(all= do.call(pmax, have))
    

    Or using dplyr

    transmute(have, all= pmax(A, B, C))
    #    all
    #1   b
    #2   a
    #3   c
    

    data

    have <- structure(list(A = c("", "a", ""), B = c("b", "", ""), 
     C = c("", 
    "", "c")), .Names = c("A", "B", "C"), class = "data.frame", 
    row.names = c("1", "2", "3"))