gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
in R with dplyr how can you rename char values in a dataframe?
- User
in R with dplyr how can you rename char values in a dataframe?
- Assistant
In R, you can use the
dplyrpackage to rename character values in a dataframe using themutatefunction along withrecodeorcase_when. Here's how you can do it:Using
recode()The
recode()function is useful for simple renaming of specific values in a column.# Load dplyr library(dplyr) # Create a sample dataframe df <- data.frame( id = 1:5, category = c("dog", "cat", "bird", "dog", "fish") ) # Print original dataframe print(df) # Rename values in the 'category' column df_renamed <- df %>% mutate(category = recode(category, "dog" = "canine", "cat" = "feline", "bird" = "avian", "fish" = "aquatic")) # Print renamed dataframe print(df_renamed)