I am trying to replace a bunch of words in a variable and thought of using case_when. But it doesn't seem to work right for me. Can someone help me out here, please? Example with just two words replacement,
Yes, this is same as what you are suggesting:
df <- df%>%
mutate(Country = case_when(
Country == "US" ~ "USA",
Country == "CAN" ~ "Canada",
TRUE ~ ""
))
Your code works for me. Are you sure that your variable name in your data frame (df) is called Country? I really can't help any more unless you provide a full reproducible example. See here for how to create one:
Again, your code looks fine to me. So to figure out your problem, you'll need to post a reproducible example including data. Please see the link in the previous post for more information.
Thanks @nirgrahamuk and @mfherman
After restarting, it works magically! Thanks for working on this!
Quick question - In this case, I kept blank ("") for cases not true. However, if there were few more countries and I wanted to keep them as is (with their original names), then what would be the best way to do.
Glad it's working. That's one reason it's so import to provide a reprex -- often there are stray objects in your environment that cause surprising errors. A reprex will always run in a clean environment.
If you don't want to change other rows, you can do the following which will return the original value of Country for those that don't match you case statement.
df %>%
mutate(
Country = case_when(
Country == "US" ~ "USA",
Country == "CAN" ~ "Canada",
TRUE ~ Country
)
)