Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset by date in R

Tags:

r

I am trying to make a subset from my data frame excluding those previous to 01/01/2012. The date format is in %d-%-m-%y and the program already knows it is a date. The data frame is TA, the variable is DATE_OLD. I have tried : new <- subset(TA, TA$JDATE_OLD<"01-01-2012"), with obvious no success.

It returns me that $ is an invalid operator for atomic vectors. Any help would be apreciated. Thanks.

like image 475
DaJunger Avatar asked Oct 17 '25 15:10

DaJunger


1 Answers

You need to have the proper comparison.

Let's start with an arbitrary data frame:

R> df <- data.frame(date=seq(as.Date("2015-01-01"), \
+                         as.Date("2015-12-01"), by="month"), \
+                   value=1000+(0:11)*42)
R> df
         date value
1  2015-01-01  1000
2  2015-02-01  1042
3  2015-03-01  1084
4  2015-04-01  1126
5  2015-05-01  1168
6  2015-06-01  1210
7  2015-07-01  1252
8  2015-08-01  1294
9  2015-09-01  1336
10 2015-10-01  1378
11 2015-11-01  1420
12 2015-12-01  1462
R> 

Now, if you want all dates past August, you simply do index for greater-equal the cut-off value -- and make sure it is a Date type too:

R> df[ df$date > as.Date("2015-08-01"), ]
         date value
9  2015-09-01  1336
10 2015-10-01  1378
11 2015-11-01  1420
12 2015-12-01  1462
R> 
like image 69
Dirk Eddelbuettel Avatar answered Oct 20 '25 04:10

Dirk Eddelbuettel