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

Time:03-09

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)

CodePudding user response:

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('d', month), sprintf('d', day)))
identical(Time1, WantedOutput)
#[1] TRUE
  •  Tags:  
  • r
  • Related