在R中为多个列使用aggregate函数

如何解决在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 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res