【问题标题】:Lubridate: expand minutes output to have a length of 3Lubridate:将分钟输出扩展为长度为 3
【发布时间】:2018-05-04 09:44:26
【问题描述】:

我正在尝试做的是获得 lubridate 以使转换的微小部分始终具有 3 的长度。这是为了进一步处理具有统一的长度。例如,时间 12:00 转换为 12H 00M 0S,而不是默认输出 12H 0M 0S。我在 hm() 的帮助中看不到任何内容,因此可能需要使用 lubridate 包之外的内容。

下面是这个想法的一些示例代码:

library (lubridate)
df <- data.frame("Time" = c("13:04", "13:55", "8:00", "8:45"))
df$Time <- hm(df$Time)

# Desired output
# 13H 04M 0S
# 13H 55M 0S
# 8H 00M 0S
# 8H 45M 0S

【问题讨论】:

  • M 有必要吗? as.character(strptime(df$Time, "%H:%M"), "%H %M %S") 返回时间为 13 04 00。

标签: r lubridate


【解决方案1】:

这段代码会得到你想要的输出:

library (lubridate)
df <- data.frame("Time" = c("13:04", "13:55", "8:00", "8:45"))

paste0(hour(hm(df$Time)), "H ", sprintf("%02d", minute(hm(df$Time))), "M 0S")
"13H 04M 0S" "13H 55M 0S" "8H 00M 0S"  "8H 45M 0S" 

但是,我不知道您打算进行哪种“进一步处理”,但这种格式不允许进行后续时间/数字计算。

hour(hm(df$Time)) #gives the hours
minute(hm(df$Time)) #gives the minutes
sprintf("%02d", ...argument2...) # forces the 2nd argument call (here the minutes) of that function to consist of 2 characters, which adds the zeroes when needed 
paste0() #pastes the hours and minutes together as 1 string, with the string "H " inbetween and the string "M 0S" at the end

【讨论】:

  • 谢谢!你能解释一下这是如何工作的吗?我使用这种方式的原因是我从 excel 导入一个文件,其中时间以一种非常奇怪的格式存储,R 不会作为串行时间导入。然后将这些数据作为字符进行操作,然后将其更改为数字,以便稍后在非常简单的设置中使用。因此不需要以 POSIX 样式存储它。
  • 当然,为了清楚起见,我会在上面添加答案。
猜你喜欢
  • 2023-01-05
  • 1970-01-01
  • 2018-05-24
  • 2018-12-27
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
相关资源
最近更新 更多