[英]Transform number chain into date
I am trying to transform a list of numbers (eg 20200119) into a valid date (here: 2020-01-19)我正在尝试将数字列表(例如 20200119)转换为有效日期(此处为:2020-01-19)
This is my trial data:这是我的试用数据:
df <- data.frame(c(20200119, 20180718, 20180729, 20150502, 20010301))
colnames(df)[1] = "Dates"
And this is what I tried so far:这是我到目前为止尝试过的:
df <- as_date(df)
df <- as.Date.numeric(df)
df <- as.Date.factor(df)
Neither of them works unfortunately.不幸的是,它们都不起作用。 I also tried to seperate the numbers, but I couldn't achieve either.
我也试着把数字分开,但我都做不到。
Can somebody help me?有人可以帮我吗?
Convert it to a character
and convert it then to a Date
with given format %Y%m%d
:将其转换为
character
,然后将其转换为具有给定格式%Y%m%d
的Date
:
as.Date(as.character(df$Dates), "%Y%m%d")
#[1] "2020-01-19" "2018-07-18" "2018-07-29" "2015-05-02" "2001-03-01"
Another option using strptime
with the right format
like this:使用
strptime
和正确format
的另一种选择是这样的:
df <- data.frame(c(20200119, 20180718, 20180729, 20150502, 20010301))
colnames(df)[1] = "Dates"
df$Dates2 <- strptime(df$Dates, format = "%Y%m%d")
df
#> Dates Dates2
#> 1 20200119 2020-01-19
#> 2 20180718 2018-07-18
#> 3 20180729 2018-07-29
#> 4 20150502 2015-05-02
#> 5 20010301 2001-03-01
Created on 2023-01-12 with reprex v2.0.2创建于 2023-01-12,使用reprex v2.0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.