gpt4 book ai didi

reshape 和均值计算

转载 作者:行者123 更新时间:2023-12-01 23:42:44 25 4
gpt4 key购买 nike

我有全年沿海拔梯度收集的气候数据。形状像这样:

clim <- read.table(text="alti    year    month    week    day    meanTemp    maxTemp    minTemp
350 2011 aug. 31 213 10 14 6
350 2011 aug. 31 214 12 18 6
350 2011 aug. 31 215 10 11 9
550 2011 aug. 31 213 8 10 6
550 2011 aug. 31 214 10 12 8
550 2011 aug. 31 215 8 9 7
350 2011 sep. 31 244 9 10 8
350 2011 sep. 31 245 11 12 10
350 2011 sep. 31 246 10 11 9
550 2011 sep. 31 244 7.5 9 6
550 2011 sep. 31 245 8 10 6
550 2011 sep. 31 246 8.5 9 8", header=TRUE)

我正在尝试 reshape 这些数据,以便每个高度只有一行,并计算每个月和全年的平均数据。如果能变成那样就好了:

alti    mean_year(meanTemp)   mean_year(maxTemp)   mean_aug.(meanTemp)   mean_aug.(maxTemp)   mean_sep.(meanTemp)   [...]
350 10.333 12.667 10.667 14.3 10 ...
550 8.333 9.833 8.667 10.333 7.766 ...

执行此 reshape 和计算有什么想法吗?

最佳答案

您可以使用 data.table 和 dcast:

library(data.table)

setDT(clim)

merge(

clim[, list("mean_temp_mean_year" = mean(meanTemp), "max_temp_mean_year" = mean(maxTemp)), by = alti]
,
dcast(clim[, list("mean_temp_mean" = mean(meanTemp), "max_temp_mean" = mean(maxTemp)), by = c("alti","month")], alti ~ month, value.var = c("mean_temp_mean","max_temp_mean"))
,
by = "alti")

我已经改变了一些变量的名称,你的顺序并不完美,但之后可以重新排序/重命名

关于 reshape 和均值计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587160/

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