2016-08-03 65 views
0

R將讀取爲日期,並將其正確解釋爲日期。我想弄清楚我的數據有多少行有重複的日期。R將不會正確地循環日期 - 重新解釋爲不是日期

test <- as.Date(final_data$DateCancelled, format = "%m/%d/%Y") 
dd <- subset(test, test >= "2016-07-01") 
length(which(dd=="2016-07-01")) 

任何日期我填寫的長度(其中()),它會正確地返回具有該日期爲$ DateCancelled VAR的行數。

但是,每當我嘗試循環這個,它都不會將它讀作日期。例如:

for (d in dd) { 
+  print(d) 
+ } 

返回這些「日期」

[1] 17009 
[1] 17009 
[1] 17009 
[1] 16988 
[1] 16989 
[1] 17009 
[1] 16996 
[1] 16996 

爲什麼它重新演繹到這個東西,顯然不是一個日期嗎?我並不十分確定它是如何解釋它的。

編輯#1:我要澄清,我真正想要做的是循環遍歷

length(which(date=="2016-07-01") 
以上

,並有超過它在DD每次約會循環。我希望它循環並告訴我每個日期,$ DateCancelled變量中有多少行具有該日期。

+0

'17009' =='2016-07-27' - 看看'Date' – thelatemail

+0

@ZheyuanLi這個現在將打印日期,但什麼?我真的希望將for循環與以下內容結合:「length(which(dd =」2016-07-01「)」,其中日期是循環的。當我嘗試將它與for循環提供上面,它打印的只是它出現的那一行的## – mjmaz

+0

@ZheyuanLi上面編輯的父文章 – mjmaz

回答

0

下面是做到這一點的一種方法:

### first create some sample data that looks like final_data$DateCancelled 

sample_dates<-append(seq(as.Date('2016-01-01'),as.Date('2016-01-10'),by = 1), 
       seq(as.Date('2016-01-01'),as.Date('2016-01-03'),by = 1) 
       ) 

### find the unique values that exist and put them in a list 

unique_dates<-list(dates=unique(sample_dates)) 

###loop through each value of date within the original data set which in this case is "sample_dates" and output counts to "unique_dates" list 

for(i in 1:length(unique_dates$dates)){ 

unique_dates$counts[[i]]<-length(subset(sample_dates, 
             sample_dates==unique_dates$dates[[i]])) 

    } 

### format output as data frame 
final_output<-data.frame(unique_dates) 

> final_output 
     dates counts 
1 2016-01-01  2 
2 2016-01-02  2 
3 2016-01-03  2 
4 2016-01-04  1 
5 2016-01-05  1 
6 2016-01-06  1 
7 2016-01-07  1 
8 2016-01-08  1 
9 2016-01-09  1 
10 2016-01-10  1