如何在R中增加分钟数

问题描述 投票:1回答:1

我有一个带有时间(例如:10.24)和分钟(例如:31)列的数据框。

我想添加这两列。结果列将为10.24 + 31(min)= 10.55。我尝试使用,但时间错误。

dput(stack_data)
structure(list(time = c("10:24", "10:40"), timeInMin = c(31L, 
23L)), row.names = c(19L, 23L), class = "data.frame")

我尝试过这样:

stack_data$time <- (hm(stack_data$time))
stack_data$timeInMin <- hms((stack_data$time) + (stack_data$timeInMin))

输出:

time         timeInMin
10H 24M 0S    10:24:31
10H 40M 0S    10:40:23

我得到了错误的答案。你能建议我怎么做吗?谢谢。

r time lubridate
1个回答
2
投票

我们可以使用as.ITime中的data.table

library(data.table)
stack_data$time <- as.ITime(paste0(stack_data$time, ":00"))
stack_data$timeInMin <- stack_data$time +
                    as.ITime(paste0("00:", stack_data$timeInMin, ":00"))
stack_data$timeInMin
#[1] "10:55:00" "11:03:00"

或使用hm

library(lubridate)
hm(stack_data$time)  + minutes(stack_data$timeInMin)
#[1] "10H 55M 0S" "10H 63M 0S"
© www.soinside.com 2019 - 2024. All rights reserved.