0

I have the following data:

ID X1 X2 X3
1 94 94 NA
2 72 NA NA
3 87 NA 87
4 NA 78 NA
5 67 67 67

I would like to generate an output by selecting only one value per row from X1-3 so the output would appear as below:

ID X
1 94
2 72
3 87
4 78
5 67

I have tried using unite which merges the data but does not remove the NA value.

E-B-2443
  • 1
  • 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Apr 04 '23 at 23:33

1 Answers1

-1

We could use coalesce:

Here we create a new column X that contains the first non-NA value from the columns X1, X2, and X3 and then we select column ID and X:

library(dplyr)

df %>% 
  mutate(X = coalesce(X1, X2, X3)) %>% 
  select(ID, X)

  ID  X
1  1 94
2  2 72
3  3 87
4  4 78
5  5 67
TarJae
  • 72,363
  • 6
  • 19
  • 66