R语言-文件行名重复,对行名重命名

R语言对重复的行名进行重命名操作

在read.table读取文件时出现了行名重复的情况,会导致报错:

文件内容:

attachments-2024-03-nJHxLoaW6600dafdc659b.png报错信息:

attachments-2024-03-TUax1sWT6600db369917a.png

此时需要对重复的行名进行重命名处理,方法一:

先不读取行名,使用make.names函数给行命名:

d<-read.table("test.xls", header = T, check.names = F)
row.names(d)<-make.names(d[,1],TRUE)

查看:

attachments-2024-03-smp2GaSN6600dd1e6cda1.png

此时只需要把文件多余列删除:

d<-d[,-1]

方法二,写循环重命名:

d<-read.table("test.xls", header = T, check.names = F)
> uniname <- unique(d[,1])
> rowname <- d[,1]
> for (i in 1:length(uniname)) {
+     count = -1
+     for (j in 1:length(rowname)) {
+         if (rowname[j] == uniname[i]) {
+             count = count + 1
+             if (count > 0) {
+                 rowname[j] = paste0(uniname[i], ".", count)
+             }      
+         }
+     }
+ }
> rownames(d) <- rowname

attachments-2024-03-YQ6D8Iyk6600e1429759d.png

参考:

https://www.cnblogs.com/liujiaxin2018/p/16325320.html

https://www.jianshu.com/p/10733715536f





  • 发表于 2024-03-25 10:29
  • 阅读 ( 205 )
  • 分类:R

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
每天学习一点点
每天学习一点点

32 篇文章

作家榜 »

  1. omicsgene 658 文章
  2. 安生水 328 文章
  3. Daitoue 167 文章
  4. 生物女学霸 120 文章
  5. 红橙子 78 文章
  6. CORNERSTONE 72 文章
  7. xun 68 文章
  8. rzx 67 文章