magrittr and date objects

南楼画角 提交于 2019-12-04 04:41:45

问题


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.


回答1:


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

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




回答2:


An "all-in magrittr solution" also works. Given the recent, sharp increase in the use of pipe operators, quite a few people have commented that an excessive exposure to pipe operators (and aliases) may hurt their eyes. Thus the spoiler block.

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

# [1] 9



回答3:


I particularly find the naming of operations in magrittr very annoying. In the given example, I would use the bizarro pipe, works like a charm

library(magrittr)
as.Date("2014-10-10") - as.Date("2014-10-1") %>% as.numeric
## [1] "1970-01-10"
as.Date("2014-10-10") - as.Date("2014-10-1") ->.; as.numeric(.)
## [1] 9

Going even further, while you'd need 3 pipes to get the week difference in the following example (I don't like the parenthesis solution that @zx8754 presented because I think it defeats the purpose of using pipes in the first place), you could have it with just 1 bizarro.

as.Date("2014-10-10") %>% subtract(as.Date("2014-08-1")) %>% as.numeric %>% divide_by(7)
## [1] 10
as.Date("2014-10-10") - as.Date("2014-08-1") ->.; as.numeric(.)/7
## [1] 10

I'm not saying that using the bizarro is the solution, I just think that magrittr could be improved, that's all.



来源:https://stackoverflow.com/questions/28148257/magrittr-and-date-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!