将时间转换为"HMS";R中的字符格式 [英] Converting Time to 'HMS" Character Format in R

查看:41
本文介绍了将时间转换为"HMS";R中的字符格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列日期时间,格式为"2000-11-21 10:01:01",2000-11-21 00:02:01',2000-11-21 00:00:06.我想创建一个新列,将时间设置为HMS格式,例如,在上述3个日期中,它将返回"HMS","MS","S".我会尝试通过以下方式进行操作,但我想知道是否有更简便的方法:

I have a column of date times formatted like '2000-11-21 10:01:01', 2000-11-21 00:02:01', 2000-11-21 00:00:06. I would like to create a new column that would set the time to an HMS format for example, in the 3 dates above, it would return 'HMS', 'MS', 'S'. I would try doing it the following way but I was wondering if there was an easier way to do it:

ifelse(
  grepl("00:00:", datecolumn), "S", 
        ifelse(grepl("00:", datecolumn), "MS", "HMS")
)

输出:

 datecolumn                 HMS
2000-11-21 10:01:01         HMS
2000-11-21 00:02:01          MS
2000-11-21 00:00:06           S
2000-11-21 00:00:10           S
2000-11-21 00:10:06          MS
2000-11-21 00:00:07           S
2000-11-21 10:00:06         HMS

推荐答案

您可以将lubridate软件包与 paste 一起使用,如下所示:

You could use the lubridate package along with paste like this:

require(lubridate)
df$new_col <- paste(ifelse(hour(df$date) > 0, "H", ""), 
                    ifelse(minute(df$date) > 0, "M", ""), 
                    ifelse(second(df$date) > 0, "S", ""), sep = "")

这篇关于将时间转换为"HMS";R中的字符格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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