'The result of `difftime` is character, how can I get only number

The result of difftime is Time difference of -1 days, how can I only get -1 ? (only want the number) . Thanks!

difftime(as.Date('2022-3-1'),as.Date('2022-3-2'),units=c("days")) 
r


Solution 1:[1]

You can use as.numeric() to get a numeric vector with the time difference.

as.numeric(difftime(as.Date('2022-3-1'),as.Date('2022-3-2'),units=c("days"))) 
#> [1] -1

This will get you a numeric vector:

str(as.numeric(difftime(as.Date('2022-3-1'),as.Date('2022-3-2'),units=c("days"))))
#>  num -1

You might want to have a look at ?difftime, it gives a nice overview on how difftime object can be used. ?as.numeric also provides complementary information.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1