R - 将日期和时间字段转换为具有HHMMSS格式的POSIXct [英] R - converting date and time fields to POSIXct with HHMMSS format

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

问题描述

我有一个数据文件,其中有三列:

I have a data file which has three columns thus:

20010101 000000  0.833
20010101 000500  0.814
20010101 001000  0.794
20010101 001500  0.772
...

相当清楚的人眼,前两个是日期和时间。我需要把它们转换成一个POSIXct(或者其他的东西,如果它更好,但我有限的过去的经验处理时间戳在R是使用POSIXct)。通常,使用read.table将其拉入,我将使用:

As is fairly clear to human eyes, the first two are date and time. I need to convert them into a POSIXct (or something else if it's better, but my limited past experience of dealing with timestamps in R is to use POSIXct). Normally, having pulled it in with read.table, I would use:

df$DateTime <- as.POSIXct(paste(df$Date, df$Time), format="%Y%m%d %H%M%S")

但是,第二列似乎失去了前导零(可能是通过类型强制?),因此它不能正常工作。

However, the second column seems to lose its leading zeroes (probably through a type coercion?), and thus it doesn't work correctly.

我看过将日期作为整数和时间作为R 中的POSIXct的因子,以及将两列日期和时间数据转换为一个,但都使用带有分隔符的时间,例如:,因此没有相同的问题。

I've looked at Combine date as integer and time as factor to POSIXct in R and Converting two columns of date and time data to one, but both are using times with delimiters such as :, and so don't have the same problem.

如何将这些列转换成POSIXct?

How can I convert these columns to a POSIXct, please?

推荐答案

你很亲密。以下简单强制将前两列作为字符串读取,从而保存前导零。

You were very close. The following "simply" forces the first two columns to be read as character strings, which saves the leading zeros.

R> df <- read.table(text="20010101 000000  0.833
20010101 000500  0.814
20010101 001000  0.794
20010101 001500  0.772", 
+ header=FALSE, colClasses=c("character", "character", "numeric"), 
+ col.names=c("Date", "Time", "Val"))
R> df
      Date   Time   Val
1 20010101 000000 0.833
2 20010101 000500 0.814
3 20010101 001000 0.794
4 20010101 001500 0.772

现在您正在尝试只是工作:

Now what you were attempting "just works":

R> df$DateTime <- as.POSIXct(paste(df$Date, df$Time), format="%Y%m%d %H%M%S")
R> df
      Date   Time   Val            DateTime
1 20010101 000000 0.833 2001-01-01 00:00:00
2 20010101 000500 0.814 2001-01-01 00:05:00
3 20010101 001000 0.794 2001-01-01 00:10:00
4 20010101 001500 0.772 2001-01-01 00:15:00
R> 

这篇关于R - 将日期和时间字段转换为具有HHMMSS格式的POSIXct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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