Split string into two variables with additional string functions in R

Viewed 32

I have a variable called time and it is written in the form of "1 year, 3 months" or "1 year" or "1 months". I want to extract the month and year into two separate variables. I am not sure how to do that.

1 Answers

If it is a column in a dataset, we can use str_extract

library(dplyr)
library(stringr)
df1 %>% 
   mutate(year = str_extract(time, "\\d+\\s+year"),
       month = str_extract(time, "\\d+\\s+months"))

-output

             time   year    month
1 1 year, 3 months 1 year 3 months
2           1 year 1 year     <NA>
3         1 months   <NA> 1 months

data

df1 <- structure(list(time = c("1 year, 3 months", "1 year", "1 months"
)), class = "data.frame", row.names = c(NA, -3L))
Related