How do you extract only the number from the result of subtracting two dates?

Viewed 681

When I subtract two dates in R, I get the result seen below.

Result of subtracting two dates in R

How would you extract only the number from this result without getting all the associative text? Is there a way to do it without having to write a parsing function?

1 Answers

We can convert to numeric wiwth as.numeric/as.double

as.numeric(diffObj)

based on the

methods(class = 'difftime')

According to ?difftime

The as.double method returns the numeric value expressed in the specified units. The units of a "difftime" object can be extracted by the units function, which also has a replacement form


A reproducible example would be

out <- Sys.Date() - (Sys.Date() - 2)
out
#Time difference of 2 days
as.numeric(out)
#[1] 2

units(out)
#[1] "days"
Related