Woelfchen99
Woelfchen99

Reputation: 1

Is there a way in R to merge two variables (or columns) despite both containing missing values?

So, my data is structured roughly as follows:

Groups A B C
First 3.5 NA NA
Second NA 4.3 NA
Third NA NA 5.2

To make life easier, I would like a way to create a new column "AB" where I get |AB | |---- | |3.5 | |4.3 | |NA |

I tried using the pivot.longer function, but this gives me an error message "Error in build_longer_spec(): ! Selections can't have missing values."

Could anyone help with this? Appreciate it!

Upvotes: 0

Views: 25

Answers (1)

akrun
akrun

Reputation: 887068

We could use coalesce which selects the first non-NA element from each row of the columns passed

library(dplyr)
df1 <- df1 %>%
   mutate(AB = coalesce(A, B))

Upvotes: 1

Related Questions