gpt4 book ai didi

r - 汇总每月金额,然后获取所有每月金额的平均值

转载 作者:行者123 更新时间:2023-12-02 03:44:27 24 4
gpt4 key购买 nike

下面的列表是使用以下代码段的时间序列中每个月对应的数据总和:

aggregate(data, by=list(Year=format(DateTime, "%Y"), Month=format(DateTime, "%m")), sum, na.rm=TRUE)

Year Month x
1 1981 01 62426.43
2 1982 01 70328.87
3 1983 01 67516.34
4 1984 01 64454.00
5 1985 01 78801.46
6 1986 01 73865.18
7 1987 01 64224.96
8 1988 01 72362.39
9 1981 02 74835.16
10 1982 02 75275.58
11 1983 02 67457.39
12 1984 02 64981.99
13 1985 02 56490.10
14 1986 02 62759.89
15 1987 02 65144.44
16 1988 02 67704.67

这部分很简单......但我在尝试获取每个月所有月度总和的平均值(即每个月总和的一个平均值)时遇到了困难如果我执行以下操作:

aggregate(data, by=list(Month=format(DateTime, "%m")), sum, na.rm=TRUE)

我只是得到时间序列中所有月份的总和,这是我不想要的。我可以在一个聚合语句中实现所需的结果,还是需要更多代码...任何帮助将不胜感激。

最佳答案

您也可以通过一次调用aggregate来完成此操作:

aggregate(data, 
by=list(Year=format(DateTime, "%Y"), Month=format(DateTime, "%m")),
FUN= function(x){ sum(x, na.rm=TRUE)/sum(!is.na(x))}
)

关于r - 汇总每月金额,然后获取所有每月金额的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9163857/

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