-2

How to merge this into 1 column?

df <- data.frame(a = c("1", "2", NA, NA), b = c(NA, NA, "3", "4"), c = c(NA, "5", "6", NA), stringsAsFactors = F)

I just want to get All values from b into a without NA. So a should be: "1", "2", "3", "4". (Now is the need of choosing columns from more than 2 in df)

This works not good: df$a <- df$b[!is.na(df$b)]

Peter.k
  • 1,475
  • 23
  • 40
  • 1
    [Relevant...](https://stackoverflow.com/questions/19253820/how-to-implement-coalesce-efficiently-in-r) – Sotos Sep 12 '17 at 13:02
  • See linked post, which has many solutions which work with multiple columns. For example, as suggested by akrun below, try: `dplyr::coalesce(df$a, df$b, df$c)` – zx8754 Sep 12 '17 at 13:12

1 Answers1

1

We can use pmax

df$a <- do.call(pmax, c(df, na.rm = TRUE))

Or with coalesce

library(dplyr)
df %>%
   mutate(a = coalesce(a,b))
#  a    b
#1 1 <NA>
#2 2 <NA>
#3 3    3
#4 4    4
akrun
  • 874,273
  • 37
  • 540
  • 662