简体   繁体   中英

Is there a way to make a 2 digit year into a 4 digit year in r

I started learning r. We have to tidy up a dataset. The date column has the date as May_08. The column has to be separate by month and year. Ex: from May_08 to May 2008. This is the code that I have so far.

dataset %>%
  separate(date, c("month","year")) 

You could use strftime . Just paste a day in front of the string beforehand.

x <- "May_08"

strftime(as.Date(paste(1, x), format="%d %b_%y"), "%b %Y")
# [1] "May 2008"

You can also use lubridate .

x <- "May_08"
library(lubridate)
paste(month(parse_date_time(x, "my"), label = T), year(parse_date_time(x, "my")), sep = " ")
# [1] "May 2008"

If you know the year breaking 20th century from 21st century years in your series, a simple ifelse statement should do. In the example, 1990 is the breaking year, so:

yrs <- c(91,94,97,00,03,06,09,12,15,18,21)
yrs <- ifelse(yrs>90, yrs+1900, yrs+2000)
> print(yrs)
[1] 1991 1994 1997 2000 2003 2006 2009 2012 2015 2018 2021

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM