2012-10-24 20 views
1

我試圖計算每月產品(二進制文件)的年度總數https://echange-fichiers.inra.fr/get?k=Jr3tvgeKnWUiC1B0MMY。所以我有12個文件,我必須計算總和。下面給出的代碼運行良好,但我需要的是將每個文件乘以當年那個月份的天數,然後計算總和。對於我而言,這些數據是2000年(閏年)年,所以我想通過31和文件號2 29等繁殖文件號爲1的結果....如何使用R指定2000年每個月的天數?

files<- list.files("C:\\jung file_2000_img", "*.img", full.names = TRUE) 
x<- do.call(rbind,(lapply(files, readBin , double() , size = 4 , n=360 * 720 , signed =TRUE))) 
results <- colSums(x) 
fileName <- sprintf("C:\\annual_ET2000_without999_1.img") 
writeBin(as.double(results), fileName, size = 4) 

從詹姆的答案,這將計算的天數:

numDays <- function(month,year){ 
as.numeric(strftime(as.Date(paste(year+month%/%12,month%%12+1,"01",sep="-"))-1,"%d")) 
     } 

那麼現在如何將它應用到我的代碼上面?我的意思是,我想借此結果爲每個文件,並通過類似的天數乘以:

file1*numDays(1,2000)+file2*numDays(2,2000)+file3*numDays(3,2000) 
      .............file12*numDays(12,2000) 

回答

4

這裏是之前在這裏使用的一招:計算第一下一個個月,並然後回去一天得到當前個月的最後一天:

R> seq(as.Date("2000-02-01"), as.Date("2001-01-01"), by="1 month") 
[1] "2000-02-01" "2000-03-01" "2000-04-01" "2000-05-01" "2000-06-01" 
[6] "2000-07-01" "2000-08-01" "2000-09-01" "2000-10-01" "2000-11-01" 
[11] "2000-12-01" "2001-01-01" 
R> seq(as.Date("2000-02-01"), as.Date("2001-01-01"), by="1 month") - 1 
[1] "2000-01-31" "2000-02-29" "2000-03-31" "2000-04-30" "2000-05-31" 
[6] "2000-06-30" "2000-07-31" "2000-08-31" "2000-09-30" "2000-10-31" 
[11] "2000-11-30" "2000-12-31" 

然後使用POSIXlt表示其中有場「月日」:

R> as.POSIXlt(seq(as.Date("2000-02-01"), as.Date("2001-01-01"), 
+    by="1 month") - 1)$mday 
[1] 31 29 31 30 31 30 31 31 30 31 30 31 
R> sum(as.POSIXlt(seq(as.Date("2000-02-01"), as.Date("2001-01-01"), 
+      by="1 month") - 1)$mday) 
[1] 366 
R> 
+0

或只是'diff(seq(as.Date(「2000-01-01」),as.Date(「2001-01-01」),by =「1 month」))'? – flodel

+0

Doh。是的,那也應該如此。 –

+0

Thanks.My問題是如何應用到我的代碼上面? – sacvf