Using the "format" argument in as.Date ()
I am trying to convert "07,29,30" to date format using as.Date () in R.
(Note that the string format is "mm, dd, yy", July 29, 1930)
So, I used the following code:
as.Date("07,29,30", format = "%m,%d,%y")
But the year I am returning is 2030, not 1930. How can I tell R to convert the value to a date that is a century earlier?
source to share
Since year values ββbetween 00 and 68 are encoded as 20 per century. From the documentation strptime
, this appears to be the reason for this.
"Year without century (00-99). Input values ββ00 to 68 prefix to 20 and 69 to 99 to 19 - this is the behavior specified in 2004 and 2008 POSIX, but they also say" Expected in a future version which was referred to by default from a two-digit year, there will be a change. "
You can use the below code to recode it.
d <- as.Date("07,29,30", format = "%m,%d,%y")
> as.Date(ifelse(d > today(), format(d, "19%y-%m-%d"), format(d)))
[1] "1930-07-29"
source to share
I'll put it anyway:
# use this library
library(lubridate)
# convert to the format (your way or you acn use lubridate)
dateconvert <- as.Date("07,29,30", format = "%m,%d,%y")
# get the year
inputYear <- year(dateconvert)
# convert the year
year(dateconvert) <- ifelse(inputYear > 2000, 1900 + (inputYear %% 100), inputYear)
source to share