'In R dplyr, rename a value based on its value in another column

I am sure this has been asked before but would really appreciate any help as I am a bit confused.

In R, I have a dataframe with rows for plants' Latin names and their common names. Using dplyr, I want to change the common name if the Latin name equals something specific.

i.e. if Latin_name == 'xyz', rename Common_name to 'abc'

I think I know how to do it with the mutate() function, but this adds an entire new column - I'd prefer to rename the values in the original column. Any help would be great, thank you so much.



Solution 1:[1]

With dplyr:

your_data %>%
  mutate(Common_name = case_when(
    Latin_name == 'xyz' ~ 'abc',
    TRUE ~ Common_name)
  )

In base R:

your_data[your_data$Latin_name == 'xyz', 'Common_name'] <- 'abc'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gregor Thomas