如何解决在R中为多个列使用aggregate函数
我有以下数据:
dat <- structure(list(Year = c(1979L,1979L,1980L,1980L),Month = c(1L,1L,2L,2L),Day = c(1L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,17L,18L,19L,20L,21L,22L,23L,24L,25L,26L,27L,28L,29L,30L,31L,29L),Rainfall = c(1,35.5,20.3,2.5,32,66.8,1.8,5.3,11.7,40.4,45.7,15.3,21.6,10.5,26.2,54.1,1.5,26.9,39.4,1.3,95.6,10.2,5.1,4.1,2.9,0.5,2.1,15.7,14.2,28.7,134.2,26.3,2.3,2.8,0.3,0.8,3.3,9.1,31.5,24.6,18.5,37.1,111.3,4.3,21.1,3.1,15.8,30.7,6.4,68.6,97.5,64.3,47.3,8.7,53.9,6.9,20.9,94,7.4,10.9,81.8,1,12.3,41.9,85.9,74.4,13.8,79.9,117.7,16.5,31.2,4.6,7.1,2,4.8,3.8,94.2,1.8),test = c(1,1.8)),row.names = c(1L,32L,33L,34L,35L,36L,37L,38L,39L,40L,41L,42L,43L,44L,45L,46L,47L,48L,49L,50L,51L,52L,53L,54L,55L,56L,57L,58L,59L,366L,367L,368L,369L,370L,371L,372L,373L,374L,375L,376L,377L,378L,379L,380L,381L,382L,383L,384L,385L,386L,387L,388L,389L,390L,391L,392L,393L,394L,395L,396L,397L,398L,399L,400L,401L,402L,403L,404L,405L,406L,407L,408L,409L,410L,411L,412L,413L,414L,415L,416L,417L,418L,419L,420L,421L,422L,423L,424L,425L),class = "data.frame")
这是1979年至1980年每日降雨量的样本数据。共有四列:年,月,日,降雨量和检验。
我想得到:
(1) Mean annual total per column. In this example,the average of the two years.
So,get the annual total first then get the average across the years.
I will be applying this for data with 60 columns from 1979 to 2017.
我不知道如何在R. Im中使用以下命令来执行此操作,但这仅适用于一列:
dat2<-aggregate(Rainfall~Year,dat,FUN=sum,na.rm=T,na.action=NULL)
mean(dat2$Rainfall)
dat3<-aggregate(test~Year,na.action=NULL)
mean(dat3$test)
在R中有简单的方法吗?现在,我正在按列手动进行操作。
对此我将不胜感激!
解决方法
在aggregate
中,您可以使用cbind
传递多个变量,并使用colMeans
获得平均值:
dat3<-aggregate(cbind(Rainfall,test)~Year,dat,FUN=sum,na.rm=T,na.action=NULL)
colMeans(dat3[-1])
但是,如果有很多列,则最好以长格式获取数据,然后summarise
将它们:
library(dplyr)
dat %>%
tidyr::pivot_longer(cols = c(Rainfall,test)) %>%
group_by(Year,name) %>%
summarise(sum = sum(value,na.rm = TRUE)) %>%
summarise(mean = mean(sum))
,
仅使用aggregate()
和/或colMeans()
的另一种方法,显示了如何选择许多列而不必命名它们:
# Sum
aggregate(dat[4:ncol(dat)],by = list(Year = dat$Year),FUN = sum,na.rm = T,na.action = NULL)
# Mean by year
aggregate(dat[4:ncol(dat)],FUN = mean,na.action = NULL)
# Mean without grouping per year
colMeans(dat[4:ncol(dat)])
输出:
> aggregate(dat[4:ncol(dat)],na.action = NULL)
Year Rainfall test
1 1979 833.1 833.1
2 1980 1492.6 1492.6
> aggregate(dat[4:ncol(dat)],na.action = NULL)
Year Rainfall test
1 1979 14.12034 14.12034
2 1980 24.87667 24.87667
> colMeans(dat[4:ncol(dat)])
Rainfall test
19.5437 19.5437
编辑:如果它们是混合中应保留为非数字的一些非数字列,则可以将dat[4:ncol(dat)]
替换为Filter(is.numeric,dat[4:ncol(dat)]
,请参见以下示例:
> dat$test <- as.character(dat$test)
> aggregate(Filter(is.numeric,dat[4:ncol(dat)]),na.action = NULL)
Year Rainfall
1 1979 833.1
2 1980 1492.6
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。