R語言實現兩文件對應行列字符替換
阿新 • • 發佈:2018-07-13
pack nbsp mode none 安裝 lse 規則 改變 2.x
假設存在文件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語言實現兩文件對應行列字符替換