g.f.l g.f.l - 2 months ago 7
R Question

Empty data frame from Date selection

I have a data frame with 3262 rows and 10 columns. One of the columns has date with format

YY-MM-DD
. I want to store all the rows with 10 different dates in a different data frame so I tried :

newdata= df[df$Date %in% as.Date(c('2011-08-05','2012-1-13','2012-03-2','2014-04-01')),]


but nothing. I thought it might need to specify again the format so I tried:

df$Date <- as.Date( as.character(df$Date), "%d-%m-%y")

newdata= df[df$Date %in% as.Date(c('2011-08-05','2012-1-13','2012-03-2','2014-04-01')),]


All I get is an empty data frame saying
no data available in table
. At which point I made the mistake (something stupid I guess)?

Answer

I created an example:

set.seed(1)
df=data.frame(col1=seq(1,10),
    col2=seq(1,0),
    Date=as.Date(floor(runif(min=15550,max=17000,n=10)),origin="1970-01-01"))
> df
   col1 col2       Date
1     1    1 2013-08-17
2     2    0 2014-01-19
3     3    1 2014-11-06
4     4    0 2016-03-06
5     5    1 2013-05-17
6     6    0 2016-02-21
7     7    1 2016-04-28
8     8    0 2015-03-14
9     9    1 2015-01-27
10   10    0 2012-10-26

Using the same code you provided:

newdata= df[df$Date %in% as.Date(c('2013-08-17','2015-01-27')),]

Gives me

> newdata
  col1 col2       Date
1    1    1 2013-08-17
9    9    1 2015-01-27

Are you sure that str(df$Date) shows you really have a Date format?

> str(df$Date)

     Date[1:10], format: "2013-08-17" "2014-01-19" "2014-11-06" "2016-03-06" "2013-05-17" "2016-02-21" "2016-04-28" "2015-03-14" "2015-01-27" "2012-10-26"