One solution is to use rollmean()
function from library zoo
to calculate moving average.
There is some confusion with data frame names in your question (p31 and p29), so I will use p 29.
p29$dt=strptime(p29$dt, "%Y-%m-%d %H:%M:%S")
library(zoo)
#Make zoo object of data
temp.zoo<-zoo(p29$ambtemp,p29$dt)
#Calculate moving average with window 3 and make first and last value as NA (to ensure identical length of vectors)
m.av<-rollmean(temp.zoo, 3,fill = list(NA, NULL, NA))
#Add calculated moving averages to existing data frame
p29$amb.av=coredata(m.av)
#Add additional line for moving average in red
ggplot(p29, aes(dt, ambtemp)) + geom_line() +
geom_line(aes(dt,amb.av),color="red") +
scale_x_datetime(breaks = date_breaks("5 min"),labels=date_format("%H:%M")) +
xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Tempreture")+
ggtitle("Node 29")
If line colors should appear in legend, then aes()
in ggplot()
and geom_line()
has to be modified and scale_colour_manual()
should be added.
ggplot(p29, aes(dt)) + geom_line(aes(y=ambtemp,colour="real")) +
geom_line(aes(y=amb.av,colour="moving"))+
scale_x_datetime(breaks = date_breaks("5 min"),labels=date_format("%H:%M")) +
xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Tempreture")+
scale_colour_manual("Lines", values=c("real"="black", "moving"="red")) +
ggtitle("Node 29")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…