R语言实现两文件对应行列字符替换(解决正负链统一的问题)

假设存在文件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文件

  

 

 

 

 

posted @ 2018-07-13 19:31  橙子牛奶糖  阅读(1413)  评论(0编辑  收藏  举报