R語言實現兩檔案對應行列字元替換

來源:互聯網
上載者:User

標籤: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_57hanchipkg_ame<-as.matrix(kg_ame);kg_amefor (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語言實現兩檔案對應行列字元替換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.