R将数字转换为时间 [英] R convert number into time

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

问题描述

有人在Excel中给了我非常糟糕的数据,其中日期(例如2015年7月1日)是20150701,时间(例如11:41:23)是114123.有超过50,000行数据,我需要将所有这些转换为正确的日期和时间对象.这些不是任何时代的秒数,它只是没有破折号或冒号的日期或时间.

Someone gave me really bad data in Excel, where the date (such as July 1, 2015) is 20150701 and the time (such as 11:41:23) is 114123. There are over 50,000 rows of data and I need to convert these all into proper date and time objects. These aren't the number of seconds from any epoch, it is just the date or time without the dashes or the colons.

我将它们导入到数据框中,并使用ymd()函数转换了日期,但是我找不到一个可以做到这一点的函数,hms()给了我一个错误:

I imported them into a data frame and converted the dates using the ymd() function, but I can't find a function to do that for time, hms() gives me an error:

package(lubridate)
df <- readWorksheetFromFile(file="cktime2012.xls", sheet=1)
df$date <- ymd(df$date)
df$time <- hms(df$time)
# Warning message:
#  In .parse_hms(..., order = "HM", quiet = quiet) :
#   Some strings failed to parse

,在运行最后一行之前,我得到一个看起来像这样的数据框.一旦运行了最后一行,TIMEIN列就会变成所有NA:

and I get a data frame that looks like this before running the last line. Once I run the last line, the TIMEIN column turns into all NA's:

DATEIN      TIMEIN  etc...
2012-02-01  200000  etc...
etc...

对于所有50,000行,我都需要它看起来像这样.我将POSIXct包含在标签中,因为我不知道是否可以使用它来帮助转换:

I need it to look like this for all 50,000 rows. I included POSIXct as a tag, because I don't know if there could be a way to use that to help convert:

DATEIN      TIMEIN      etc...
2012-02-01  20:00:00    etc...
etc...

推荐答案

如果 TIMEIN 始终为六个字符(即,上午10点之前的时间前导零),则可以执行以下操作:

If TIMEIN is always six characters (i.e., there's a leading zero for times before 10 AM), then you can do this:

df$TIMEIN = paste0(substr(df$TIMEIN,1,2),":",substr(df$TIMEIN,3,4),":", substr(df$TIMEIN,5,6))
df$TIMEIN = hms(df$TIMEIN)

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

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