如何在R中增加分钟的时间 [英] How to add minutes to time in R

查看:47
本文介绍了如何在R中增加分钟的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a data frame with time(e.g: 10.24) and minute(e.g:31) columns.

我想添加这两列.结果列将为10.24 + 31(min)= 10.55.我尝试了的问题,但时间不正确.

I want to add those two columns. Resultant column would be 10.24+31(min)=10.55. I tried with lubridate but it is giving wrong times.

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

我得到一个错误的答案.你能建议我怎么做吗?谢谢.

I am getting a wrong answer. Can you please suggest me to how to do it? Thanks.

推荐答案

我们可以使用 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"

这篇关于如何在R中增加分钟的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆