在r中的数据帧中按年求和
我有一个包含两列(年份和降水量)的数据框架。在单列中,列出的年份从1900年开始,到2014年结束,再从1900年开始。在另一列中,我有相应年份的降水量值。现在我想把1900年和1901年的降水量加起来,直到2014年。我的数据如下所示:在r中的数据帧中按年求和,r,R,我有一个包含两列(年份和降水量)的数据框架。在单列中,列出的年份从1900年开始,到2014年结束,再从1900年开始。在另一列中,我有相应年份的降水量值。现在我想把1900年和1901年的降水量加起来,直到2014年。我的数据如下所示: Year Precipitation 1900 4.826 1901 37.592 2014 14.224 1900 45.974 1901 46.228 2014 79.502 1900 52.578 190
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)
谢谢,这似乎太复杂了。为什么不把总数分开计算呢
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])
s.1900Try data.table
library(data.table)
frame=fread('precipitation.csv',header=TRUE,sep=',')
frame[, sum(Precipitation), by = Year]
1行--尝试:
参考资料:为什么年有重复的值,是季度还是月份还是其他什么?
aggregate(frame['Precipitation'], by=frame['Year'], sum)