Subsetting a dataframe for a specified month and year

Since you didn’t provide a data set I made my own from the link you provided. Your method works for me and I get an empty data set only if I don’t meet both of the conditions supplied (month and year) so I’m guessing you’re you’re attempting to subset a date series (month and year) that doesn’t exist (but can’t tell for certain without the code you’re using). Here’s the code I used:

sales <- read.table(text="2372  Kansas KS2000111 HUMBOLDT, CITY OF    ATRAZINE    1.3 05/07/2006
9104  Kansas KS2000111 HUMBOLDT, CITY OF    ATRAZINE   0.34 07/23/2006
9212  Kansas KS2000111 HUMBOLDT, CITY OF    ATRAZINE   0.33 02/11/2007
2094  Kansas KS2000111 HUMBOLDT, CITY OF    ATRAZINE    1.4 05/06/2007
16763 Kansas KS2000111 HUMBOLDT, CITY OF    ATRAZINE   0.61 05/11/2009
1076  Kansas KS2000111 HUMBOLDT, CITY OF METOLACHLOR   0.48 05/12/2002
1077  Kansas KS2000111 HUMBOLDT, CITY OF METOLACHLOR    0.3 05/07/2006")

sales$V9 <- as.Date(sales$V9, "%m/%d/%Y")
names(sales)[9] <- 'date'
subset(sales, format.Date(date, "%m")=="05" & format.Date(date, "%y")=="07")
#    V1     V2        V3        V4   V5 V6       V7  V8       date
#4 2094 Kansas KS2000111 HUMBOLDT, CITY OF ATRAZINE 1.4 2007-05-06

subset(sales, format.Date(date, "%m")=="05" & format.Date(date, "%y")=="10")
#[1] V1   V2   V3   V4   V5   V6   V7   V8   date
#<0 rows> (or 0-length row.names)

Leave a Comment