How to use if_else and mutate to substitute the value in charactor vector as condition?

Viewed 88

I want to generate one column in data with previous value if the condition in if_else are/aren`t consistent with, the value will be the same as the original column.

Here is the code:

iristest <- iris
iristest %>% mutate(Species=if_else(Species=='setosa','Setosa',Species))

Here is the error:

#Error: Problem with `mutate()` column `Species`.
#i `Species = if_else(Species == "setosa", "Setosa", Species)`.
#x `false` must be a character vector, not a `factor` object.

How do I solve the problem? I know it can be solved with a char function such as stringr, but I hope and think it could be solved in a mutate way.

2 Answers

You can use the following -

library(dplyr)

iristest %>% mutate(Species = factor(if_else(Species=='setosa',
                              'Setosa',as.character(Species))))

Since, Species is of type factor you can use factor specific functions to recode the value. Here, we can use fct_recode from forcats.

iristest %>% mutate(Species= forcats::fct_recode(Species, Setosa = 'setosa'))

In base R, we can just set the levels

levels(iristest$Species)[levels(iristest$Species) == 'setosa'] <- "Setosa"
Related