R语言日期转换年份偏移:如何用gsub替换字符串第三个点为.19?
Hey there! Let's tackle that date formatting problem you're facing. The issue with as.Date() interpreting your two-digit years as 2000s instead of 1900s is super common, and we've got a couple of solid solutions for you.
Solution 1: Using gsub to Add the 19 Prefix
You mentioned wanting to use gsub to modify the year part—here's how to do it with a regex that targets the final segment of your date strings:
The regex ^(\\d{2}\\.\\d{2}\\.)(\\d{2})$ splits your date into two capture groups:
- The first group (
\\d{2}\\.\\d{2}\\.)grabs the day and month portion (e.g., "03.04." from "03.04.30") - The second group (
\\d{2}$) captures the two-digit year at the end of the string
We then replace the original string with the first group, followed by "19", then the second group. Here's the code in action:
x <- c("03.04.30", "02.06.32", "01.11.33", "10.10.31") # Modify the year to include the 19 prefix x_formatted <- gsub("^(\\d{2}\\.\\d{2}\\.)(\\d{2})$", "\\119\\2", x) # Convert to Date object as.Date(x_formatted, format = "%d.%m.%Y")
Running this will give you dates like 1930-04-03, 1932-06-02—exactly what you need!
Solution 2: Using cutoff with %y Format (No gsub Needed)
An even simpler approach is to use the %y format specifier (for two-digit years) and set the cutoff argument in as.Date(). This tells R when to switch between 1900s and 2000s for two-digit years.
Since your years are all 30 or higher, setting cutoff = 29 will make R interpret any two-digit year greater than 29 as 1900s:
x <- c("03.04.30", "02.06.32", "01.11.33", "10.10.31") # Directly convert with cutoff parameter as.Date(x, format = "%d.%m.%y", cutoff = 29)
This gives you the same correct dates without needing to modify the original string first—pretty handy!
内容的提问来源于stack exchange,提问作者Julian

