Dealing with Date in R language

In R there is a class called Date. If we want to get the components of a date variable or date string, we can use the following function to do it.

toNumerics <- function(Date)
stopifnot(inherits(Date, c(“Date”, “POSIXt”)))
day <- as.numeric(strftime(Date, format = “%d”))
month <- as.numeric(strftime(Date, format = “%m”))
year <- as.numeric(strftime(Date, format = “%Y”))
list(year = year, month = month, day = day)

The following code uses the above function to deal with date and datestr.

today <- Sys.Date()
mydatecom <- toNumerics(today)
day <- mydatecom$day
month <- mydatecom$month
year <- mydatecom$year
mydatestr <- paste(year,formatC(month, width=2, flag=”0″),formatC(day, width=2, flag=”0″), sep=”-“)
data1 <- subset(data, as.POSIXct(data$Date)>=as.POSIXct(mydatestr))

mydatestr likes like “2017-03-10”. By using as.POSIXct can convert the datestr to the class POSIXct and then used in the comparison.

This entry was posted in R, R/S-Plus. Bookmark the permalink.

Leave a Reply