问题
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