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.
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
df1 <- structure(list(time = c("1 year, 3 months", "1 year", "1 months"
)), class = "data.frame", row.names = c(NA, -3L))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.