This question already has an answer here:
这个问题在这里已有答案:
- as.Date with two-digit years 3 answers
as.Date有两位数年份3个答案
I have a character vector with dates, formatted in this way (this is just an example):
我有一个带有日期的字符向量,以这种方式格式化(这只是一个例子):
x <- c("03.04.30", "02.06.32", "01.11.33", "10.10.31")
x < - c(“03.04.30”,“02.06.32”,“01.11.33”,“10.10.31”)
and so on. I'm using the as.Date
function as such:
等等。我正在使用as.Date函数:
x <- as.Date(x, format = "%d.%m.%Y")
x < - as.Date(x,format =“%d。%m。%Y”)
and it's working but it's returning years for me in the 2000s, and not in the 1990s as I would like.
它正在发挥作用,但它在2000年代为我带来了多年,而不是像我想的那样在20世纪90年代。
My idea is to simply replace the third instance of the period in each element of x
with .19
using gsub
but I cannot come up with a regular expression to do so and I've looked all over the place online and really cannot figure this out.
我的想法是简单地使用gsub替换x的每个元素中的句点的第三个实例,但是我无法想出一个正则表达式来执行此操作并且我在网上查看了所有这些地方并且实际上无法弄清楚这一点。
I've also tried using the substr
function to replace the 6th character of each element of x
with .19
but it's simply replacing the whole character string. Being able to do either of those effectively would help me!
我也尝试使用substr函数用.19替换x的每个元素的第6个字符,但它只是替换整个字符串。能够有效地做到这两点对我有帮助!
I know I'm probably overlooking a simpler solution but please help me I'm pulling my hair out trying to figure this out.
我知道我可能会忽略一个更简单的解决方案,但请帮助我,我正在试着想出这个问题。
2 个解决方案
#1
2
You could do:
你可以这样做:
x <- c("03.04.30", "02.06.32", "01.11.33", "10.10.31")
x <- gsub("(\\d{2})$", "19\\1", x)
as.Date(x, format = "%d.%m.%Y")
To get:
[1] "1930-04-03" "1932-06-02" "1933-11-01" "1931-10-10"
This assumes the data is consistently formatted otherwise you might want to rethink the regular expressions.
这假定数据的格式一致,否则您可能需要重新考虑正则表达式。
#2
0
Try the following regex.
试试以下正则表达式。
x2 <- sub("\\.(\\d{2})$", ".19\\1", x)
x2
#[1] "03.04.1930" "02.06.1932" "01.11.1933" "10.10.1931"
as.Date(x2, format = "%d.%m.%Y")
#[1] "1930-04-03" "1932-06-02" "1933-11-01" "1931-10-10"
#1
2
You could do:
你可以这样做:
x <- c("03.04.30", "02.06.32", "01.11.33", "10.10.31")
x <- gsub("(\\d{2})$", "19\\1", x)
as.Date(x, format = "%d.%m.%Y")
To get:
[1] "1930-04-03" "1932-06-02" "1933-11-01" "1931-10-10"
This assumes the data is consistently formatted otherwise you might want to rethink the regular expressions.
这假定数据的格式一致,否则您可能需要重新考虑正则表达式。
#2
0
Try the following regex.
试试以下正则表达式。
x2 <- sub("\\.(\\d{2})$", ".19\\1", x)
x2
#[1] "03.04.1930" "02.06.1932" "01.11.1933" "10.10.1931"
as.Date(x2, format = "%d.%m.%Y")
#[1] "1930-04-03" "1932-06-02" "1933-11-01" "1931-10-10"