Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

r - Subsetting a dataframe for a specified month and year

I have a dataframe where the first column is a date in d/m/y format and the second is a numeric value (sales).

I want to create subsets for each month of one year (eg. 11/11, 12/11 etc). I tried the code suggested in this answer: subset a data.frame with multiple conditions

and it works when the condition on the month is imposed:

subset(sales, format.Date(date, "%m")=="11")

but it returns an empty subset with error message invalid 'x' argument when I add the year condition:

subset(sales, format.Date(date, "%m")=="11" & format.Date(date, "%y")=="11")

I am using R 2.10.1-2 on Ubuntu 10.04, thanks for the help you can give.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...