-2

I have the following CSV file:

               f        , c
        1,19/11/2014 12:00,0.01
        2,19/11/2014 13:00,0.01
        3,20/11/2014 15:00,0.01
        4,20/11/2014 16:00,0.01
        5,20/11/2014 17:00,0.01  
        6,20/11/2014 19:00,0.01  
        7,20/11/2014 22:00,0.20  
        8,20/11/2014 23:00,0.03
        9,21/11/2014 16:00,0.01
        10,21/11/2014 17:00,0.01

I read the CSV file by using the following:

library(strucchange)
ts1<-read.csv (file.choose())

I would like to filter all the rows between given dates (DATE1 and DATE2).

DATE1 <- as.Date("20/11/2014 16:00", format = "%d/%m/%Y %H:%M")
DATE2 <- as.Date("20/11/2014 23:00", format = "%d/%m/%Y %H:%M")

So, I'll get the following rows in dataframe ts2:

           f        , c
    3,20/11/2014 15:00,0.01
    4,20/11/2014 16:00,0.01
    5,20/11/2014 17:00,0.01  
    6,20/11/2014 19:00,0.01  
    7,20/11/2014 22:00,0.20

For transformation between ts1 and ts2 I tried the following:

    ts1$f<-as.Date(ts1$f, format = "%d/%m/%Y %H:%M")
    ts2<-ts1[ts1$f %in% DATE1:DATE2, ]
    ts2$f<-as.factor (ts2$f)

And afterwards I'll be able to use the following:

z<-read.zoo(ts2, tz = "", format = "%d/%m/%Y %H:%M", sep = ",")
bp <- breakpoints(z ~ 1, h = 2)

but I get the following error:

>     bp <- breakpoints(z ~ 1, h = 2)
Error in `[[<-.data.frame`(`*tmp*`, i, value = c(1L, 11L, 6L, 3L, 4L,  : 
  replacement has 10 rows, data has 5
Avi
  • 2,247
  • 4
  • 30
  • 52

1 Answers1

1

One thing to keep in mind with R is the Date class only works with days and not time. Thus in this case strptime or as.POSIXct is the function to use and not as.Date. Also on you convert the date/time to POSIX object, I suggest not converting back to a factor.

#Enter the data
ts1<-read.table(header = TRUE, sep=",", text="row, f        , c
        1,19/11/2014 12:00,0.01
                2,19/11/2014 13:00,0.01
                3,20/11/2014 15:00,0.01
                4,20/11/2014 16:00,0.01
                5,20/11/2014 17:00,0.01  
                6,20/11/2014 19:00,0.01  
                7,20/11/2014 22:00,0.20  
                8,20/11/2014 23:00,0.03
                9,21/11/2014 16:00,0.01
                10,21/11/2014 17:00,0.01 ")
#convert to date/time
ts1$f<-as.POSIXct(ts1$f, format="%d/%m/%Y %H:%M")
#create limits
DATE1 <- as.POSIXct("20/11/2014 16:00", format = "%d/%m/%Y %H:%M")
DATE2 <- as.POSIXct("20/11/2014 23:00", format = "%d/%m/%Y %H:%M")
#subset data from between limits
ts2<-subset(ts1, f>=DATE1 & f<=DATE2)
Dave2e
  • 22,192
  • 18
  • 42
  • 50