如何根据同一行的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)

相关推荐
咖啡の猫1 小时前
数据库的基本概念
数据库
小卓笔记2 小时前
keepalived应用
linux·服务器·数据库
姑苏洛言3 小时前
30天搭建消防安全培训小程序
前端
八股文领域大手子4 小时前
Leetcode32 最长有效括号深度解析
java·数据库·redis·sql·mysql
鹏神丶明月天4 小时前
mybatis_plus的乐观锁
java·开发语言·数据库
左钦杨4 小时前
Nuxt2 vue 给特定的页面 body 设置 background 不影响其他页面
前端·javascript·vue.js
yechaoa4 小时前
【揭秘大厂】技术专项落地全流程
android·前端·后端
SelectDB技术团队4 小时前
天翼云:Apache Doris + Iceberg 超大规模湖仓一体实践
大数据·数据库·iceberg·doris·数据湖·湖仓一体·天翼云
MurphyChen5 小时前
🤯 一行代码,优雅的终结 React Context 嵌套地狱!
前端·react.js
逛逛GitHub5 小时前
推荐 10 个受欢迎的 OCR 开源项目
前端·后端·github