Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create e dates in R from year, month, day?

I have a dataset where the creator saved the date in three seperate variables. My goal is to convert these three date variables into a single numerical variable that keeps the chronological order. To do that, I first pasted together my 3 variables. However, I`m seemingly unable to convert this into a numeric variable. See below for some example code and the output I want. There must be some easy way to do this in R but everything I try results in errors.

#example data
day <- c(1,2,13)
month <- c(1,2,12)
year <- c(2020, 2020, 2020)


#paste variables
Time <- paste(year, formatC(month, width = 2, flag = 0), formatC(day, width = 2, flag = 0))

WantedOutput <- c(20200101, 20200202, 20201213)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

paste by default has sep = " ". Use paste0 and change the output to numeric.

Time <- as.numeric(paste0(year, formatC(month, width = 2, flag = 0),
                                formatC(day, width = 2, flag = 0)))

identical(Time, WantedOutput)
#[1] TRUE

You can also use sprintf

Time1 <- as.numeric(paste0(year, sprintf('%02d', month), sprintf('%02d', day)))
identical(Time1, WantedOutput)
#[1] TRUE
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading