Trying to convert a character variable for gender to a numeric.
df_enrollment_clean$sex is a string variable: "Male" or "Female." I need to convert to a 1 for males or a 2 for females. Using the below; I'm completely new to R so I appreciate the help!
Grace
sexObserved <- factor(df_enrollment_clean$sex) #This is 1 for female, 2 for male
sexObserved[df_enrollment_clean$sex=="Male"] <- "1"
sexObserved[df_enrollment_clean$sex=="Female"] <- "2"
sexObserved <- factor(sexObserved)
recode is probably the most straightforward approach for your case, but the code below shows a few options. I've converted to numeric, rather than character/factor. Did you want the new 1 and 2 values to be coded as factor? If so, it would make more sense to keep the original coding for sex and just convert that to factor class.
library(tidyverse)
# Fake data
set.seed(2)
d = data.frame(sex = sample(c("Male","Female"), 10, replace=TRUE))
d$sex[5] = NA
d
#> sex
#> 1 Male
#> 2 Male
#> 3 Female
#> 4 Female
#> 5 <NA>
#> 6 Female
#> 7 Male
#> 8 Male
#> 9 Male
#> 10 Female