简体   繁体   中英

Transform number chain into date

I am trying to transform a list of numbers (eg 20200119) into a valid date (here: 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 :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM