1

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.

0

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.