2015-03-31 56 views
1

我有一個包含兩列(年份和降水量)的數據框。在一列中,年份的排列順序是1900年開始,2014年結束,1900年開始。在另一列中,我有相應年份的降水值。現在,我想補充的1900所有的降水值1和1901年1至最多2014我的數據是這樣的:在r中的數據框中連續按年數總和

Year Precipitation 

1900 4.826 
1901 37.592 
2014 14.224 
1900 45.974 
1901 46.228 
2014 79.502 
1900 52.578 
1901 22.30 
2014 15.25 

結果應該是這樣的:

Year Precipitation 

1900 103.378 
1901 106.12 
2014 108.976 

到目前爲止,我寫了一個代碼,但它不起作用,如果有人可以修復它?

data=read.table('precipitation.csv',header=T,sep=',') 
frame=data.frame(data) 
cumcum=tapply(frame$Precipitation, cumsum(frame$year==1), FUN=sum, na.rm=TRUE) 

感謝

+0

你爲什麼有年份重複的值,是他們宿舍或幾個月或什麼? – smci 2015-03-31 07:56:59

回答

0

這似乎過於複雜。爲什麼不分開做這些款項呢?

s.1900 <- sum(frame$Precipitation[frame$year == 1900]) 
s.1901 <- sum(frame$Precipitation[frame$year >= 1901 & frame$year <= 2013]) 
s.2014 <- sum(frame$Precipitation[frame$year == 2014]) 

它確實會讓您的代碼稍後可讀。

2

嘗試data.table

library(data.table) 
frame=fread('precipitation.csv',header=TRUE,sep=',')  
frame[, sum(Precipitation), by = Year]