Search code examples
rmagrittr

magrittr and date objects


I just noticed that when I subtract two dates from one another and then try to cast to to a numeric value with magrittr (%>%) I get a date, where as if I simply wrap the date difference in as.numeric() I get the number of days difference as a numeric value. See the simple example below:

## version 1
as.Date("2014-10-10") - as.Date("2014-10-1") %>% as.numeric
## return value -->  "1970-01-10"

## version 2 (returning the value that I actually want)
as.numeric(as.Date("2014-10-10") - as.Date("2014-10-1"))
## return value --> 9

While this isn't a big deal here, I would like to understand why this is happening to be able to predict other (for me unexpected) behaviors.


Solution

  • Try this, without extra brackets, pipe is computed 1st, then subtraction.

    (as.Date("2014-10-10") - as.Date("2014-10-1")) %>% as.numeric