This seems to be very easy to do but I couldn't find an answer. I have two variables in my dataframe regarding Area names. I want to create a final Area variable using this two variables. If Area2 is missing then just use Area1 values but if Area2 is not missing the use Area2 values.
Area Area2 Goal
ABC ABC
ABC ABC
AAA AAA AAA
AA-A AAA AAA
A AA AAA AAA
data <- data.frame(Area1 = c("ABC", "ABC", "AAA", "AA-A", "A AA"),
Area2 =c("", "", "AAA", "AAA", "AAA"))
My tried is below but I am obtaining numeric values for my final variable instead of string values (even using the as.factor option).
data$AreaFinal <- ifelse(is.na(data$Area2), data$Area1, data$Area2)
data$AreaFinal <- ifelse(is.na(data$Area2), as.factor(data$Area1), data$Area2)
Does this code look ok? In my real data Area1 is a factor and Area 2 is a character.
Thank you in advance! Marvin
Aucun commentaire:
Enregistrer un commentaire