Converting numeric gender variable

Trying to convert character variable ("1", "0") to Male and Female respectively from a dataset using Rstudio and dplyr or tidyverse

Following prompts result in error:
library(dplyr)
ds <- tibble(ds$sex)
ds <- ds %>%
mutate(factor(ds$sex,
levels = c ("1","0"),
labels = c ("Male","Female")

library(tidyverse)
ds <- tibble(ds$sex)
ds <- ds %>%
mutate(sex=factor(sex,
levels = c("1","0"),
labels = c ("Male","Female"))

Thank you so much

Hi,

Welcome to the RStudio community!

Here is an example on how to do this

library(dplyr)

myData = data.frame(
  id = 1:6,
  gender = c(0,0,1,0,0,1) %>% as.character()
)

myData %>% mutate(gender = ifelse(gender == "0", "Male", "Female"))
#>   id gender
#> 1  1   Male
#> 2  2   Male
#> 3  3 Female
#> 4  4   Male
#> 5  5   Male
#> 6  6 Female

Created on 2022-01-10 by the reprex package (v2.0.1)

Hope this helps,
PJ

3 Likes

In {base}

myData = data.frame(
  id = 1:6,
  gender = as.character(c(0,0,1,0,0,1))
)

myData$gender <- ifelse(myData$gender == "0","Male","Female")

summary(myData)
#>        id          gender         
#>  Min.   :1.00   Length:6          
#>  1st Qu.:2.25   Class :character  
#>  Median :3.50   Mode  :character  
#>  Mean   :3.50                     
#>  3rd Qu.:4.75                     
#>  Max.   :6.00

# with factors

myData$gender <- as.factor(ifelse(myData$gender == "0","Male","Female"))
      
myData = data.frame(
  id = 1:6,
  gender = as.character(c(0,0,1,0,0,1))
)

myData$gender <- as.factor(ifelse(myData$gender == "0","Male","Female"))
summary(myData)
#>        id          gender 
#>  Min.   :1.00   Female:2  
#>  1st Qu.:2.25   Male  :4  
#>  Median :3.50             
#>  Mean   :3.50             
#>  3rd Qu.:4.75             
#>  Max.   :6.00

# with gender initially coded as integer

myData = data.frame(
  id = 1:6,
  gender = c(0,0,1,0,0,1)
)

myData$gender <- as.factor(myData$gender)
levels(myData$gender) <- c("Male","Female")
summary(myData)
#>        id          gender 
#>  Min.   :1.00   Male  :4  
#>  1st Qu.:2.25   Female:2  
#>  Median :3.50             
#>  Mean   :3.50             
#>  3rd Qu.:4.75             
#>  Max.   :6.00
1 Like