首页 文章

Chron到POSIXct

提问于
浏览
0

我有一个大数据集,在前两列中包含字符类型的日期/时间信息 .

Date     Time                    Current
1 28.02.2013 23:58:50                       NA
2 28.02.2013 23:58:50                      0.3
3 28.02.2013 23:58:51                      0.3
4 28.02.2013 23:58:51                      0.3
5 28.02.2013 23:58:57                      0.3
6 28.02.2013 23:58:58                      0.3

由于我想稍后将其转换为xts对象,我将这两列转换为包含日期和时间的POSIXct类型之一,并使用以下代码:

bigdata <- ldply (files, read.table,header=TRUE, sep = "\t", dec=".", as.is= 1:2 ) #read the tables keeping the charater format of the first two columns 
library("chron")
Time<-chron(bigdata$Date, bigdata$Time, format= c(dates= "d.m.y", times="h:m:s")) 
Time2<- as.POSIXct(paste(as.Date(dates(Time)),times(Time)%%1)) #to POSIXct

Time2中的结果是一个POSIXct对象,其中日期和时间在一列中,并给出了所需的结果:

"2013-02-01 00:02:09 CET" "2013-02-01 00:02:12 CET" "2013-02-01 00:02:13 CET" "2013-02-01 00:02:13 CET" "2013-02-01 00:02:13 CET".....

(我知道时间不同,因为我使用了之前的结果,但想法是一样的)

然而,由于一些奇怪的原因,对于一些与我之前展示的相同特征的数据集,我得到的Time2的结果证明是:

"2013-02-28 CET" "2013-02-28 CET" "2013-02-28 CET" "2013-02-28 CET" "2013-02-28 CET" "2013-02-28 CET"

(这次的时间与上面显示的数据集的摘录相同)

“时间”部分完全删除,只留下日期 . 我已经将相同的代码应用于各种数据集,并且对于大多数数据集而言它工作得很好,但是其中一个存在这个问题 .

知道为什么我得到了不同的结果吗?

                          • -编辑 - - - - - - - - - - - -----------------

我在两个对象时间和时间2上运行命令dput.Hera是结果:

> dput( head( Time2))
structure(c(1362006000, 1362006000, 1362006000, 1362006000, 1362006000, 
1362006000), class = c("POSIXct", "POSIXt"), tzone = "")

> dput( head( Time))
structure(c(15764.9991898148, 15764.9991898148, 15764.9992013889, 
15764.9992013889, 15764.9992708333, 15764.9992824074), format = structure(c("d.m.y", 
"h:m:s"), .Names = c("dates", "times")), origin = structure(c(1, 
1, 1970), .Names = c("month", "day", "year")), class = c("chron", 
"dates", "times"))

1 回答

  • 0

    为什么不在一次操作中执行它而不通过chron级对象?

    Time2<-as.POSIXct(paste(bigdata$Date, bigdata$Time), 
                      format= "%d.%m.%Y %H:%M:%S")
    
    ##########
    bigdata <- read.table(text="    Date     Time                    Current
    1 28.02.2013 23:58:50                       NA
    2 28.02.2013 23:58:50                      0.3
    3 28.02.2013 23:58:51                      0.3
    4 28.02.2013 23:58:51                      0.3
    5 28.02.2013 23:58:57                      0.3
    6 28.02.2013 23:58:58                      0.3", header=TRUE, 
          stringsAsFactors=FALSE)
    
    library("chron")
    Time<-chron(bigdata$Date, bigdata$Time, format= c(dates= "d.m.y", times="h:m:s")) 
    Time2<- as.POSIXct(paste(as.Date(dates(Time)),times(Time)%%1))
    Time2
    [1] "2013-02-28 23:58:50 PST" "2013-02-28 23:58:50 PST" "2013-02-28 23:58:51 PST"
    [4] "2013-02-28 23:58:51 PST" "2013-02-28 23:58:57 PST" "2013-02-28 23:58:58 PST"
    

相关问题