简体   繁体   中英

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.

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM