I think this is a better (more human-readable) way to do it
library(tidyverse)
all_Data <- data.frame(
stringsAsFactors = FALSE,
PersonID = c(67, 82, 67, 21, 2, 12, 45),
Favorite = c("Apple","Lemon","Orange",
"Lemon","Onion","Apple",NA)
)
all_Data %>%
mutate(
Country = case_when(
Favorite == "Apple" ~ "France",
Favorite %in% c("Lemon", "Orange") ~ "Greece",
TRUE ~ "Kenya"),
City = case_when(
Favorite == "Apple" ~ "Paris",
Favorite %in% c("Lemon", "Orange") ~ "Athens",
TRUE ~ "Nairobi"),
Continent = case_when(
Favorite %in% c("Apple", "Lemon", "Orange") ~ "Europe",
TRUE ~ "Africa")
)
#> PersonID Favorite Country City Continent
#> 1 67 Apple France Paris Europe
#> 2 82 Lemon Greece Athens Europe
#> 3 67 Orange Greece Athens Europe
#> 4 21 Lemon Greece Athens Europe
#> 5 2 Onion Kenya Nairobi Africa
#> 6 12 Apple France Paris Europe
#> 7 45 <NA> Kenya Nairobi Africa
Created on 2022-04-24 by the reprex package (v2.0.1)