I have the following:
\"0014-06-30\"
And I\'d like to change it to:
\"0000-06-30\"
How would I do this in
> x <- as.Date('0014-06-30')
> x
[1] "0014-06-30"
> library(lubridate)
> year(x)
[1] 14
> year(x) <- 0
> x
[1] "0000-06-30"
I couldn't get the specific format by converting to as.Date
. A regex
option would be
str1 <- "0014-06-30"
as.Date(str1)
#[1] "14-06-30"
sub('\\d{2}(?=-)', '00', str1, perl=TRUE)
#[1] "0000-06-30"
I would offer the following function to fix a mixed vector of two and four digit dates (where you have have formatted a string as a date if starting with a string):
library(lubridate)
two_dig_year_cnvt <- function(z, year=2017){
y <- as.numeric(format(z, '%Y'))
range <- 2017 - 2000
year(z) <- ifelse(y >= 0 & y <= range, 2000 + y,
ifelse(y > range & y <= 200, 1900 + y, y))
z
}
This says for two digit years 00-16, assume that 2000 was the intended century, and for years 17-200 assume the century was 1900. Else, return the original year. If you're dealing with 19th century dates then of course this method is a no-go.