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

相关推荐
TDengine (老段)11 分钟前
TDengine 字符串函数 CONCAT_WS 用户手册
android·大数据·数据库·时序数据库·tdengine·涛思数据
IT 小阿姨(数据库)32 分钟前
PostgreSQL 之上的开源时序数据库 TimescaleDB 详解
运维·数据库·sql·postgresql·开源·centos·时序数据库
灰小猿38 分钟前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
im_AMBER1 小时前
React 16
前端·笔记·学习·react.js·前端框架
02苏_1 小时前
ES6模板字符串
前端·ecmascript·es6
excel1 小时前
⚙️ 一次性警告机制的实现:warnOnce 源码深度解析
前端
excel1 小时前
Vue SFC 样式编译核心机制详解:compileStyle 与 PostCSS 管线设计
前端
excel1 小时前
🧩 使用 Babel + MagicString 实现动态重写 export default 的通用方案
前端
excel1 小时前
Vue SFC 编译器主导出文件解析:模块组织与设计哲学
前端
excel1 小时前
深度解析:Vue SFC 模板编译器核心实现 (compileTemplate)
前端