Home > database >  Mutate a new column based on observations present in a row
Mutate a new column based on observations present in a row

Time:10-06

I'd like to mutate a new column Gender based on the available observations present in the column Variable. Below is the dataframe

Variable <- c("Corrective surgeries undertaken on male persons","Corrective surgeries undertaken on female persons","Corrective surgeries undertaken on transgender persons")
count <- c(2,3,4)
DF <- data.frame(Variable,count)

How do I implement conditional statements to generate a new column with new observations of male, female and transgender based on the observations in the column variable?

CodePudding user response:

We could extract the substring with str_extract

library(dplyr)
library(stringr)
DF <- DF %>%
    mutate(Gender = str_extract(Variable, 'male|female|transgender'),
    Variable = str_remove_all(Variable, '\\s \\b(male|female|transgender)'))

-output

DF
                                     Variable count      Gender
1 Corrective surgeries undertaken on persons     2        male
2 Corrective surgeries undertaken on persons     3      female
3 Corrective surgeries undertaken on persons     4 transgender
  • Related