【问题标题】:How to send output to specific location through pipes in R如何通过R中的管道将输出发送到特定位置
【发布时间】:2019-12-20 05:24:16
【问题描述】:

我正在编写一个小代码,我在其中比较了两次并找出差异并以 HH:MM:SS 格式显示。

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”

我正在尝试的另一种方法是通过管道技术。但是在这里,我收到一个错误。

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 % as.numeric() %>% seconds_to_period() %>% + sprintf('%02d:%02d:%02d', 小时(.), 分钟(.), 秒(.)) sprintf(., "%02d:%02d:%02d", hour(.), minute(.), second(.)) 中的错误: 'fmt' 不是字符向量

点操作似乎不适用于这种情况。我该怎么办?

另外,有没有更好的方法来实现时间功能?

【问题讨论】:

    标签: r pipe


    【解决方案1】:

    当你使用管道时,左边的对象默认是函数的第一个输入。要阻止这种情况,请使用大括号 ({})。

    library(lubridate)
    
    difftime(s2, s1, units = "secs") %>%
       as.numeric() %>%
       seconds_to_period() %>%
      {sprintf('%02d:%02d:%02d', hour(.), minute(.), second(.))}
    
    #[1] "00:03:20"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2020-08-17
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多