比较 R 中的时间 [英] Compare time in R

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

问题描述

我有两列,比如 A 和 B(时间为 HH:MM 格式)

I have two columns, say A and B (time in HH:MM format)

  A       B
00:00   06:00

str(A) 和 str(B) 给出字符".

str(A) and str(B) gives "character."

我想做一个比较,例如,

I want to make a comparison like,e.g.,

Comment <- ifelse(hour_part(A) < hour_part(B), "Dead","NONE")

我想用 R 来做.

如何在 R 中实现?

推荐答案

使用这个测试数据:

DF <- data.frame(A = "00:00", B = "06:00", stringsAsFactors = FALSE) # test data

1) 字符类 这适用于原始字符表示:

1) character class This works with the original character representation:

hour_part <- function(x) as.numeric(sub(":.*", "", x)) # can optionally omit as.numeric
Comment <- ifelse(hour_part(DF$A) < hour_part(DF$B), "Dead", "NONE")

2) times class 如果这不是您想用 DF 做的唯一事情,那么最好先将它们转换为 "times" 类.

2) times class If this is not the only thing you want to do with DF then it might be better to first convert them to "times" class.

library(chron)

to.times <- function(x) times(paste0(x, ":00"))
DF2 <- transform(DF, A = to.times(A), B = to.times(B))
Comment <- ifelse(hours(DF2$A) < hours(DF2$B), "Dead", "NONE")

注意:下次请以可重现的形式提供测试数据.

Note: Next time please provide the test data in reproducible form.

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

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