将日期和时间字段转换为带有HHMMSS格式的POSIXct - R

14

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

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

很明显,前两个是日期和时间。我需要将它们转换为POSIXct格式(如果有更好的格式也可以,但是我过去处理R中的时间戳的经验有限,所以通常会使用POSIXct)。通常,在使用read.table导入数据后,我会使用以下代码:

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

然而,第二列似乎失去了它的前导零(可能是通过类型强制转换?),因此无法正常工作。

我查看了Combine date as integer and time as factor to POSIXct in RConverting two columns of date and time data to one,但两者都使用带有分隔符(如:)的时间,所以没有相同的问题。

请问如何将这些列转换为POSIXct呢?

3个回答

18

你很接近了。下面的代码“简单地”将前两列强制读取为字符字符串,这样可以保存前导零。

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

现在你尝试的东西“就可以工作”:

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> 

我正在按照这里描述的做,但 POSIXct 返回了 NA。 - Jack
你可能有一个因子变量。尝试使用anytime::anytime(paste(df$Date, df$Time)),它可以为你转换因子变量。 - Dirk Eddelbuettel
感谢您的回复,我有一些早期时间是像 600 这样的,它们只需要在前面加上一个 0 - Jack
所以你的输入不符合格式要求。晚上11点的新闻?很高兴你已经解决了它。 - Dirk Eddelbuettel

3
你只需要将数据作为字符导入:
txt <- "Date  Time  value
20010101 000000  0.833
20010101 000500  0.814
20010101 001000  0.794
20010101 001500  0.772
"

df <- read.table(text=txt, header=TRUE, 
                 colClasses=c("character", "character", "numeric"))

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

谢谢。我接受了第一个回答,但实质上它们是一样的 :-) - Flyto

1

你可以使用超级棒和快速的 lubridate 包。针对你的目的,请尝试以下方法:

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"))

df$mix <- paste(df$Date, df$Time)
df$mix <- parse_date_time(df$mix, 'Ymd HMS')

你只需要将正确的格式输入即可。我更喜欢使用 as.POSICct,因为它更加灵活,而且你还可以使用其他函数处理时间变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接