在R中的几列中获取月度均值的有效方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在R中的几列中获取月度均值的有效方法相关的知识,希望对你有一定的参考价值。
我有一个按日期排序的大型数据框,其中包含多个列,例如传感器,农场,围场,索引等。我正在寻找一种有效的方法来按日期和特定围场获取每月平均值。目前,我已逐列过滤,并在获得每月平均值之后将结果保存在一个数据框中,最后将每个数据框从一个列合并为一个。
r<-read.table(file = "clipboard", sep=" ",header=TRUE,na.strings = "NA",fill=TRUE)
> r
date sensor granule_id client farm paddock index mean sd
1 2016-01-05 S2 T18GXA ecofos maitenes maiz_2 PGR 83.20 3.44821
2 2016-01-05 S2 T18GXA ecofos maitenes maiz_1 PGR 80.73 5.54963
3 2016-01-05 S2 T18GXA ecofos maitenes peña_a PGR 77.63 2.31232
4 2016-01-05 S2 T18GXA ecofos maitenes peña_b PGR 77.44 3.69589
5 2016-01-05 S2 T18GXA ecofos maitenes patagua PGR 76.77 9.61289
6 2016-01-05 S2 T18GXA ecofos maitenes laurel PGR 75.02 2.10570
7 2016-01-05 S2 T18GXA ecofos maitenes pero_a PGR 74.12 6.14028
8 2016-01-05 S2 T18GXA ecofos maitenes brazo_muerto PGR 74.10 3.68202
9 2016-01-05 S2 T18GXA ecofos maitenes las_piedras PGR 71.20 6.75291
10 2016-01-05 S2 T18GXA ecofos maitenes la_isla PGR 67.52 11.96992
names(r)
unique(r$paddock)
r$date<-as.Date(as.character(r$date),"%d-%m-%Y")
el_pero_b<-r[r$paddock == 'el_pero_b',]
maiz_2<-r[r$paddock == 'maiz_2',]
los_bolos_b<-r[r$paddock == 'los_bolos_b',]
punta_estero<-r[r$paddock == 'punta_estero',]
maiz_1<-r[r$paddock == 'maiz_1',]
pero_a<-r[r$paddock == 'pero_a',]
patagua<-r[r$paddock == 'patagua',]
los_bolos_a<-r[r$paddock == 'los_bolos_a',]
brazo_muerto<-r[r$paddock == 'brazo_muerto',]
laurel<-r[r$paddock == 'laurel',]
peña_a<-r[r$paddock == 'peña_a',]
lado_estero<-r[r$paddock == 'lado_estero',]
peña_b<-r[r$paddock == 'peña_b',]
la_isla<-r[r$paddock == 'la_isla',]
las_piedras<-r[r$paddock == 'las_piedras',]
#1
el_pero_b_media<- xts(el_pero_b$mean, as.Date(as.character(el_pero_b$date),"%d-%m-%Y"))
#cob_sem<-na.locf(cob_sem, na.rm = T, fromLast = FALSE,maxgap=Inf)
el_pero_b_mensual = apply.monthly(el_pero_b,mean,na.rm=TRUE)
names(el_pero_b_mensual )<-"PGR"
el_pero_b_mensual <-data.frame(el_pero_b_mensual)
el_pero_b_mensual$Fecha <- rownames(el_pero_b_mensual)
#2
maiz_2_media<- xts(maiz_2$mean, as.Date(as.character(maiz_2$date),"%d-%m-%Y"))
#cob_sem<-na.locf(cob_sem, na.rm = T, fromLast = FALSE,maxgap=Inf)
maiz_2_mensual = apply.monthly(maiz_2_media,mean,na.rm=TRUE)
names(maiz_2_mensual )<-"PGR"
maiz_2_mensual <-data.frame(maiz_2_mensual)
maiz_2_mensual$Fecha <- rownames(maiz_2_mensual)
#3
los_bolos_b_media<- xts(los_bolos_b$mean, as.Date(as.character(los_bolos_b$date),"%d-%m-%Y"))
#cob_sem<-na.locf(cob_sem, na.rm = T, fromLast = FALSE,maxgap=Inf)
los_bolos_b_mensual = apply.monthly(los_bolos_b_media,mean,na.rm=TRUE)
names(los_bolos_b_mensual )<-"PGR"
los_bolos_b_mensual <-data.frame(los_bolos_b_mensual)
los_bolos_b_mensual$Fecha <- rownames(los_bolos_b_mensual)
答案
可能正在寻找
aggregate(cbind(mean,sd)~month_year + paddock,
transform(df, month_year = format(as.Date(date), "%m-%Y")), mean, na.rm = TRUE)
这将为您提供数据帧的mean
和mean
列的每月sd
。
以上是关于在R中的几列中获取月度均值的有效方法的主要内容,如果未能解决你的问题,请参考以下文章