I have the below dataset that is built from
help <- data.frame(var1 = c("red", NA, NA, NA, "red", "orange"),
var2 = c(NA, "lightred", "blue", "lightred", NA, NA))
var1 var2
1 red <NA>
2 <NA> lightred
3 <NA> blue
4 <NA> lightred
5 red <NA>
6 orange <NA>
And I am stuck trying to make a new variable, newvar
that simply merges the factor variables into one new column. I am hoping to get output as follows
var1 var2 newvar
1 red <NA> red
2 <NA> lightred lightred
3 <NA> blue blue
4 <NA> lightred lightred
5 red <NA> red
6 orange <NA> orange
Here was my attempt based on other threads here
help$newvar = ifelse(help$var1 == "", help$var2, help$var1)
When the variables are factors, the newvar
are numbers, which makes sense, but only variables from var1
move to newvar
. When character, again only the characters from var1
move to newvar
.
I know similar questions have been asked, but the answers didn't seem to fix this issue. Merge two factor columns in R
Is there a way to do this in dplyr too? I'll take whatever solution I can get, just curious.