2012-03-04 84 views
0

到一個子集數據框這一問題與我以前的一個,Subsetting a dataframe for a specified month and year我無法指定正確的日期格式中的R

我用命令

銷售< - read.csv(「mysales。 CSV」,colClasses =‘字符’)

獲得數據框,看起來像這樣:

row  date   pieces  income 
    1  21/11/2011  49   220.5 
    2  22/11/2011  58   261 
    3  23/11/2011  23   103.5 
    4  24/11/2011  57   256.5 

我想創建爲2011年11月我們的一個子集在我之前的問題中提供的代碼,但各種嘗試都失敗了。因此,對於檢查我在控制檯中寫道:

format.Date(sales[1,1], "%Y")=="2011" 

和答案是:

[1] FALSE 

此外:

format(as.Date(sales[1,1]), "%d/%m/%Y") 
[1] "20/11/21" 

我如何,至少,知道什麼是有發生日期格式?

我應該怎麼辦使用類似的代碼子集數據框:

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

很抱歉,如果我的問題是不明確的,但我面臨的問題是,我不清楚無論是。

(編輯正確的格式)

+0

這與您的其他問題沒有多大區別。你的日期不是真正的日期,它們只是字符串。如果仔細閱讀@ TylerRinker的回答,您會發現他所做的第一件事是使用'as.Date'替換日期列。 – flodel 2012-03-04 11:58:59

回答

1

目前,你認爲是真的日期都只是個字符的字符串。你需要使用as.Date將它們變成Date對象,並且爲了指定它們的格式(%d/%m/%Y)或者R不會爲你猜出它。

sales <- data.frame(date = c("21/11/2011", "21/11/2011", "23/11/2012", "24/11/2012"), 
        pieces = c(49,58,23,57,34), 
        income = c(220.5, 261, 103.5, 256.5, 112)) 
class(sales$date) 
# [1] "factor" 
sales$date <- as.Date(sales$date, "%d/%m/%Y") 
class(sales$date) 
# [1] "Date" 
subset(sales, format.Date(date, "%m")=="11" & format.Date(date, "%Y")=="2011") 
#   date pieces income 
# 1 2011-11-21  49 220.5 
# 2 2011-11-21  58 261.0 
+0

此方法有效。不僅僅是提供複製和粘貼代碼行,您的回答讓我明白日期的處理方式。 – 2012-03-06 06:11:41

0

只是爲了使答案更一般,我又增加了一個月。

工作數據是這樣的:

  date pieces income 
1 21/11/2011  49 220.5 
2 22/11/2011  58 261.0 
3 23/11/2011  23 103.5 
4 24/11/2011  57 256.5 
5 23/12/2011  50 240.0 

有很多方法可以做到這一點。我經常使用的一個是strsplit和lapply。

sale$date1<-as.Date(sale$date, "%d/%m/%Y") # let R know the date format 

# Create a column of months by splitting the dates into 3 parts and grabbing the middle 
# part which is months 
sale$months<-lapply(strsplit(as.character(sale$date1), "-"), function(x){x[2]}) 

# finally keep only the data for the month of November 

required<-subset(sale[which(sale$months==11),], select=-c(months,date1)) 

     date pieces income 
1 21/11/2011  49 220.5 
2 22/11/2011  58 261.0 
3 23/11/2011  23 103.5 
4 24/11/2011  57 256.5 
+0

這對於創建「月份」列會更清晰一些:'sale $ month < - as.numeric(format.Date(sale $ date1,「%m」))' – flodel 2012-03-04 12:39:48

+0

此外,您的子集中的邏輯表達式'電話可能只是'個月== 11'。 – flodel 2012-03-04 12:44:48

+0

@ flodel。感謝您的評論並展示替代方式來做到這一點。 – user1234357 2012-03-04 12:49:26