码迷,mamicode.com
首页 > 编程语言 > 详细

R语言实现两文件对应行列字符替换

时间:2018-07-13 20:17:46      阅读:538      评论:0      收藏:0      [点我收藏+]

标签:alt   命名   bubuko   splay   nbsp   安装包   pre   内容   分享图片   

假设存在文件file1.xlsx,其内容如下:

技术分享图片

存在文件file2.xlsx,其内容如下:

技术分享图片

 现在我想从第七列开始,将file2所有的字符替换成file1一样的,即第七、八、九、十列不需要改变,因为file1和file2的字符一致的(3和1,2和4);从第11列开始,file1和file2的字符不一样了。我的命名规则是从第11列开始,file2的2改为3,4改1,3改为2,1改为4;

下面是代码的实现过程:

install.packages("openxlsx") #安装openxlsx安装包
install.packages("readxl") #安装readxl安装包
install.packages("stringr")#安装stringr安装包
library("stringr")
library(readxl)
library(openxlsx)
model_57hanchip<- read_excel("E:/myproject/file1.xlsx")
kg_ame<- read_excel("E:/myproject/file2.xlsx")
model_57hanchip<-as.matrix(model_57hanchip);model_57hanchip
kg_ame<-as.matrix(kg_ame);kg_ame
for (i in 1:4){
  g=i*2+5
  j=i*2+6
  if(any(intersect(model_57hanchip[,g:j], kg_ame[,g:j])>0)==TRUE | all(kg_ame[,g:j]==0)==TRUE){
    print(c(g,j))
  }else if(all(c(1,2) %in% kg_ame[,g:j])==TRUE){
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "1", "4");
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "2", "3");
    print(c(kg_ame[,g],kg_ame[,j]))
  }else if(all(c(1,3) %in% kg_ame[,g:j])==TRUE){
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "1", "4");
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "3", "2");
    print(c(kg_ame[,g],kg_ame[,j]))
  }else if(all(c(2,4) %in% kg_ame[,g:j])==TRUE){
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "2", "3");
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "4", "1");
    print(c(kg_ame[,g],kg_ame[,j]))
  }else {
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "3", "2");
    kg_ame[,g:j] =str_replace_all(kg_ame[,g:j], "4", "1");
    print(c(kg_ame[,g],kg_ame[,j]))
  }
}
##上述的代码的意思是将1改为4,2改为3,3改为2,4改为1;
openxlsx::write.xlsx(kg_ame, file = "E:/myproject/kg_ame.xlsx") #保存为Excel文件

  

 

 

 

R语言实现两文件对应行列字符替换

标签:alt   命名   bubuko   splay   nbsp   安装包   pre   内容   分享图片   

原文地址:https://www.cnblogs.com/chenwenyan/p/9306795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!