简体   繁体   English

有没有办法在 r 中将 2 位数年份变成 4 位数年份

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

I started learning r.我开始学习r。 We have to tidy up a dataset.我们必须整理一个数据集。 The date column has the date as May_08.日期列的日期为 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.例如:从 May_08 到 2008 年 5 月。这是我迄今为止的代码。

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

You could use strftime .你可以使用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 .您也可以使用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.如果您知道系列中从 21 世纪年份打破 20 世纪的年份,则应该使用简单的ifelse语句。 In the example, 1990 is the breaking year, so:在示例中,1990 年是突破年份,因此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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