如何根据同一行的ID利用R语言对值进行求和

需求:将属于同一分组的对应的值进行求和或者求平均值

R 复制代码
#设置工作目录
> getwd()
[1] "C:/Users/86150/Documents"
> setwd("C:/Users/86150/Desktop/AA2024/RUF")
> list.files()
#读取文件
>install.packages("readxl")
>library("readxl")
> df <- read_excel("202002_RUF_Seed.xlsx")
> head(df)
# A tibble: 6 × 2
  group seed 
  <chr> <chr>
1 R1    5.33 
2 R10   1.8  
3 R10   0.45 
4 R10   5.68 
5 R10   1.48 
6 R105  0,.06

##利用函数aggregate进行分组求和
> merge_data <- aggregate(.~group,data=df,sum())

出现报错:

Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument

R 复制代码
You need to remove the color column from the x argument, since it is not being used in aggregation, but is actually the by argument.

aggregate(csv[-1], csv["color"], sum)
#   color val2 val3
# 1  blue    6   13
# 2 green    7    3
# 3   red   11    9

换一种方法还是不行:

R 复制代码
library(dplyr)
df %>% group_by(group) %>% summarise_each(funs(sum))

使用命令 class(df$seed) :检测发现SUM求和的那一列为字符串类型

1\] "character"

解决方法:

发现是因为seed列为字符型,而sum函数要求数值型,因此只需要将seed转为数值型即可:

figa1 <- df %>% mutate(seed = as.numeric(as.character(seed))) %>% group_by(group) %>% summarize(total = sum(seed))

mutate(seed = as.numeric(as.character(seed)))指的是把count转为数值型

将结果输出:保存为excel的可读形式

R 复制代码
#加载"xlsx"
library(xlsx)
library(writexl)
install.packages("openxlsx")  #如果没有这个包就安装
library(openxlsx)

write.xlsx(figa1, "C:/Users/86150/Desktop/AA2024/RUF", append = TRUE)
write_xlsx(figa1, "C:/Users/86150/Desktop/AA2024/RUF")

##这个测试成功了
install.packages("openxlsx")  #如果没有这个包就安装
library(openxlsx)
write.xlsx(figa1, file = file.path("C:/Users/86150/Desktop/AA2024/RUF", "202002ruf_seed.xlsx"))

结果如图:total列显示为每个编号的总的种子总量(备注:因为一个材料编号一般种了三个重复)

注意事项:在将数据(a.xlsx)导入r语言之前需对数据进行检测,包括sum列的数字格式类型是否为字符串,以及sum值输入时是否存在错误(例如将"."写成",";是否存在中文即非纯数字)

参考文献来源:

R语言中怎么将数据框导出成xlsx文件并规定存放目录_r语言数据导出成xlsx-CSDN博客

R 报错: x invalid 'type' (character) of argument - 橙子牛奶糖 - 博客园 (cnblogs.com)

相关推荐
console.log('npc')11 分钟前
Table,vue3在父组件调用子组件columns列的方法展示弹窗文件预览效果
前端·javascript·vue.js
用户479492835691520 分钟前
React Hooks 的“天条”:为啥绝对不能写在 if 语句里?
前端·react.js
我命由我1234539 分钟前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法
QQ14220784491 小时前
没有这个数据库账户,难道受到了sql注入式攻击?
数据库·sql
用户47949283569151 小时前
给客户做私有化部署,我是如何优雅搞定 NPM 依赖管理的?
前端·后端·程序员
C_心欲无痕1 小时前
vue3 - markRaw标记为非响应式对象
前端·javascript·vue.js
残 风1 小时前
pg兼容mysql框架之语法解析层(openHalo开源项目解析)
数据库·mysql·开源
勇往直前plus1 小时前
MyBatis/MyBatis-Plus类型转换器深度解析:从基础原理到自定义实践
数据库·oracle·mybatis
qingyun9891 小时前
深度优先遍历:JavaScript递归查找树形数据结构中的节点标签
前端·javascript·数据结构
cyhysr2 小时前
sql将表字段不相关的内容关联到一起
数据库·sql