gpt4 book ai didi

r - 在r中的数据框中连续按年求和

转载 作者:行者123 更新时间:2023-12-04 11:49:34 25 4
gpt4 key购买 nike

我有一个包含两列(年份和降水)的数据框。在单列中,年份被列出,从 1900 年开始,到 2014 年结束,再次从 1900 年开始。在另一列中,我有相应年份的降水值。现在我想将 1900 年的所有降水量添加为 1 个值,将 1901 年的所有降水量添加为 1 到 2014 年。我的数据如下所示:

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)

谢谢

最佳答案

试试数据表

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

关于r - 在r中的数据框中连续按年求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29361035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com