Home > front end >  How do I replace multiple values to another value at the same time in a column?
How do I replace multiple values to another value at the same time in a column?

Time:12-12

I have a data frame that looks like this

Sex 1 2 1 1 2 2

I want to change all 1 to "Male" and 2 to "Female"

I know there are some ways to change values in a column, but I could not find a way to change 1 and 2 at the same time with a single syntax. Is there a way?

CodePudding user response:

There are many options, but I typically favor case_when because it enables me to easily add more conditions and provides a choice in which no condition is met.

library(dplyr)

df <- tibble(sex = c(1,2,1,1,2,2))

df %>% 
  mutate(
    #if_else - if you just have two options, is very easy
    sex_ifelse = if_else(sex == 1, "Male","Female"),
    #case_when - same as if_else, but better for more levels
    sec_casewhen = case_when(
      sex == 1 ~ "Male",
      sex == 2 ~ "Female",
      #can even trow a option if another value exists
      TRUE ~ "Unknown"
    ),
    #factor - another option is to create a factor, as said in the comments
    sex_factor = factor(sex,levels = c(1,2),labels = c("Male","Female")),
    #with forcats from tidyverse you can use create a factor
    sex_recode = forcats::fct_recode(factor(sex), Male = "1", Female = "2")
    )
# A tibble: 6 x 5
    sex sex_ifelse sec_casewhen sex_factor sex_recode
  <dbl> <chr>      <chr>        <fct>      <fct>     
1     1 Male       Male         Male       Male      
2     2 Female     Female       Female     Female    
3     1 Male       Male         Male       Male      
4     1 Male       Male         Male       Male      
5     2 Female     Female       Female     Female    
6     2 Female     Female       Female     Female 

Pay attention, that depending on the function your variable will be a character or a factor.

CodePudding user response:

The simplest way to do this is by using ifelse:

df$sex <- ifelse(df$sex == 1, "Male", "Female")

Result:

df
     sex
1   Male
2 Female
3   Male
4   Male
5 Female
6 Female

Data:

df <- data.frame(sex = c(1,2,1,1,2,2))
  •  Tags:  
  • r
  • Related