Search code examples
rif-statementrecode

Recode categorical variable as new variable in R


How would I add a new categorical column to this data based on the values in the 1st column in R? Like this:

> head(df)
          common_name
1       Sailfin molly
2 Hardhead silverside
3           Blue crab

if common_name = "Sailfin molly", "Hardhead silverside", put "Fish" else, put "Crab"

> head(df)
          common_name   category
1       Sailfin molly   Fish
2 Hardhead silverside   Fish
3           Blue crab   Crab

Solution

  • Found this answer here (https://rstudio-pubs-static.s3.amazonaws.com/116317_e6922e81e72e4e3f83995485ce686c14.html#/9)

    df <- mutate(df, cat = ifelse(grepl("Sailfin molly", common_name), "Fish",
                                          ifelse(grepl("Hardhead silverside", common_name), "Fish", "Crab")))