我会将日、月和年添加到数据框中,然后使用aggregate()
.
首先将您的date
列转换为 POSIXct 对象:
d$timestamp <- as.POSIXct(d$dates,format = "%m/%d/%Y %H:%M",tz ="GMT")
然后将日期(例如 12/03/2012)放入名为 的列Date
中,试试这个:
d$Date <- format(d$timestamp,"%y-%m-%d",tz = "GMT")
接下来,按日期汇总:
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ Date,
data = d,
FUN = mean)
同样,您可以将月份放入一列(我们称之为M
月份),然后...
d$M <- format(d$timestamp,"%B",tz = "GMT")
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ M,
data = d,
FUN = mean)
或者如果你想要年月
d$YM <- format(d$timestamp,"%y-%B",tz = "GMT")
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ YM,
data = d,
FUN = mean)
如果您的数据中有任何 NA 值,您可能需要考虑这些:
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ YM,
data = d,
function(x) mean(x,na.rm = TRUE))
最后,如果你想按周平均,你也可以这样做。先生成周数,然后再使用aggregate()
。
d$W <- format(d$timestamp,"%W",tz = "GMT")
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ W,
data = d,
function(x) mean(x,na.rm = TRUE))
此版本的周数将第 1 周定义为一年中第一个星期一的那一周。星期是从星期一到星期日。