Wrapping a factor function within the transform function

Hi all,

I'm currently working with a fairly large data set from a questionnaire, and I'm in the process of recoding values within a column (specifically ones that pertain to race/background)

Within the race column, I have several NAs alongside the race that the respondent selected. What I am looking to do is rename non-missing values in that particular column and convert that column into a factor (it's currently a character column).

What I have so far is the following:

df<-transform(df, race = replace (race, !is.na(race), "LatinAm"))

This will recode any values that AREN'T missing into more simplified ones than what the raw data export provides, while leaving the NAs as NAs. I'm just looking for a way to incorporate the factor function into my above code to convert that column into a factor.

Any guidance is greatly appreciated!

Would this work for you:

# Load Libraries
library("tidyverse")

# Create Example Data
df <- tibble(
  race = sample(c("A", "B", "C", NA), size = 100, replace = TRUE))

# Wrangle Data
df |> 
  mutate(
    race = case_when(!is.na(race) ~ "LatinAm",
                     TRUE ~ race) |> as_factor())

?

1 Like

@Leon

Oh yes, that's exactly what I was looking to do. Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.