Home > Software engineering >  Extract words from observations in one column to new columns in R
Extract words from observations in one column to new columns in R

Time:08-17

Below is a hypothetical dataframe.

Category <- c("Male children 0-15 years", "Female children 0-15 years", "Male Youths 18 years",  "Female Youths 18 years")
value <- c(12, 23, 33, 45)
DF <- data.frame(Category, value)

                   Category value
1   Male children 0-15 years    12
2 Female children 0-15 years    23
3       Male Youths 18 years    33
4     Female Youths 18 years    45

I'd like to split the observations in the column Category into two, the first word and the rest of the words so that my final dataframe looks like this

                    Category gender value          new.column
1   Male children 0-15 years   Male    12 children 0-15 years
2 Female children 0-15 years Female    23 children 0-15 years
3       Male Youths 18 years   Male    33     Youths 18 years
4     Female Youths 18 years Female    45     Youths 18 years

CodePudding user response:

Use tidyr::separate:

library(tidyverse)
DF %>% 
  separate(Category, into = c("gender", "new.column"), remove = FALSE, extra = "merge")
  • Related