Phil_T Phil_T - 2 months ago 12
R Question

conditionally merge columns, r

I have a data frame that contains patient survival data. I have a column for time to last follow up and a column for time to death. If the patient died, the numerical value of time will be listed in the time to death column, and not in the time to last follow up column; and vice versa if the patient is still alive. The opposite column, so if the patient is alive I am referring to the death column, there is a "[Not Available]" character string instead of a time component. Here is an example:

follow up death
100 [Not Available]
[Not Available] 300
2000 [Not Available]


I want to conditionally merge the two columns into a single column keeping just the numerical values like this:

Time
1000
300
2000

ycw ycw
Answer Source

We can use coalesce from the dplyr package.

library(dplyr)

dt <- data_frame("follow up" = c(1000, NA, 2000),
                 "death" = c(NA, 300, NA))

dt2 <- dt %>%
  mutate(Time = coalesce(.$`follow up`, .$death))

dt2
# A tibble: 3 x 3
  `follow up` death  Time
        <dbl> <dbl> <dbl>
1        1000    NA  1000
2          NA   300   300
3        2000    NA  2000