not dealing properly with dates in R

94 views Asked by At

I am trying to use selectByDate from openair package but got stuck in my second try I have A

> A 
         date    x
23 1982-08-23  0.0
24 1982-08-24  0.0
25 1982-08-25  0.0
26 1982-08-26  9.3
27 1982-08-27  0.0
28 1982-08-28  0.2
29 1982-08-29  0.0
30 1982-08-30  0.0
31 1982-08-31  0.0
32 1982-09-01  0.0
33 1982-09-02  0.2
34 1982-09-03  0.9
35 1982-09-04  4.2
36 1982-09-05  0.0
37 1982-09-06  0.0
38 1982-09-07  1.2
39 1982-09-08  0.0
40 1982-09-09  0.0

and then

> selectByDate(A, month = 9)
         date    x
10 1982-09-01  0.0
11 1982-09-02  0.2
12 1982-09-03  0.9
13 1982-09-04  4.2
14 1982-09-05  0.0
15 1982-09-06  0.0
16 1982-09-07  1.2
17 1982-09-08  0.0
18 1982-09-09  0.0

but with B

16  1971-04-20 100511
17  1971-04-21 100795
18  1971-04-22 101008
19  1971-04-23 101292
20  1971-04-24 101577
21  1971-04-25 101862
22  1971-04-26 102220
23  1971-04-27 103372
24  1971-04-28 103662
25  1971-04-29 103807
26  1971-04-30 104025
27  1971-05-01 104316
28  1971-05-02 104462
29  1971-05-03 104681
30  1971-05-04 104900
31  1971-05-05 105047

I got

> selectByDate(B, month = 4)
Error in as.POSIXlt.default(x, tz = tz(x)) : 
  do not know how to convert 'x' to class “POSIXlt”

I am a beginner in R and I cant see why this happens. Any clue?

1

There are 1 answers

0
Ronak Shah On

Convert data to as.POSIXct class and then try :

B$date <- as.POSIXct(B$date, '%Y-%m-%d')
openair::selectByDate(B, month = 4)

You can also do this in base R :

subset(B, as.integer(format(date, '%m')) == 4)