標籤: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語言實現兩檔案對應行列字元替換