How to send output to specific location through pipes in R

寵の児 提交于 2021-02-05 08:58:31

问题


I am writing a small code where i compare two times and find the difference and display it in HH:MM:SS format.

library(magrittr)
library(lubridate)
s1 <- ymd_hms(Sys.time())
s2 <- ymd_hms(Sys.time()) +200
d1 <- seconds_to_period(as.numeric(difftime(s2, s1, units = "secs")));
d2 <-sprintf('%02d:%02d:%02d', hour(d1), minute(d1), second(d1));

d2 [1] "00:03:21"

Another way i am trying is through piping techniques. But here, i am receiving an error.

s1 <- ymd_hms(Sys.time())
s2 <- ymd_hms(Sys.time()) +200
d3 <- difftime(s2, s1, units = "secs")  %>% as.numeric() %>% seconds_to_period() %>% sprintf('%02d:%02d:%02d', hour(.), minute(.), second(.))

d3 <- difftime(s2, s1, units = "secs") %>% as.numeric() %>% seconds_to_period() %>% + sprintf('%02d:%02d:%02d', hour(.), minute(.), second(.)) Error in sprintf(., "%02d:%02d:%02d", hour(.), minute(.), second(.)) : 'fmt' is not a character vector

The dot operation seems to not be working for this case. What should I do?

Also, is there better way to implement the time function?


回答1:


When you use pipes the object on the left is the first input to the function by default. To stop that use curly braces ({}).

library(lubridate)

difftime(s2, s1, units = "secs") %>%
   as.numeric() %>%
   seconds_to_period() %>%
  {sprintf('%02d:%02d:%02d', hour(.), minute(.), second(.))}

#[1] "00:03:20"


来源:https://stackoverflow.com/questions/59420230/how-to-send-output-to-specific-location-through-pipes-in-r

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