的R - 转换的日期和时间字段,以与HHMMSS格式

的R - 转换的日期和时间字段,以与HHMMSS格式

问题描述:

POSIXct我有因此具有三列的数据文件:的R - 转换的日期和时间字段,以与HHMMSS格式

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?

你非常接近。以下“简单”强制将前两列读为字符串,这将保存前导零。

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> 

你只需要导入数据的字符:

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

谢谢。我接受了第一个答案,但这是基本相同的:-) – Flyto 2013-04-30 13:59:07

只要您可以使用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,因为它更加灵活,并且您还有其他功能可以与时间变量一起工作。