Lubridate:将分钟输出扩展为长度为 3
Lubridate: expand minutes output to have a length of 3
我想做的是 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
此代码将获得您想要的输出:
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"
但是,我不知道你打算做什么 "further processing",但是这种格式不允许后续的 time/numeric 计算。
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
我想做的是 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
此代码将获得您想要的输出:
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"
但是,我不知道你打算做什么 "further processing",但是这种格式不允许后续的 time/numeric 计算。
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