I have a data frame, and one of the columns is a mislabeled continent value called americas. I want to reassign all values with United States and Canada as North America, and Every other value labeled as Americas to be reassigned as South America.
for (i in g2$country){
if (i == "United States") {
g2$continent == 'North America"
}
}
CodePudding user response:
g2 <- g2 |> mutate("new" = ifelse(country %in% c("United States","Canada"),"North America","South America"))
If there are more labels in your country variable, you should add another ifelse() instead of "South America"
CodePudding user response:
If you want to work in a tidyverse frame, you could use case_when:
g2 %>%
mutate(continent = case_when(
country %in% c("United States", "Canada", "Mexico") ~ "North America",
TRUE ~ "South America")
)
(that TRUE ~ "South America"
is how case_when
handles ELSE
logic.)
A more generalized solution (if you have lots more than 2 continent labels) would be to build a dictionary tibble continent_lookup
with columns for country and continent and then join
that with your current g2
tibble.