There is a folder test under the default directory of R language, and there are three files under it, namely, , . Now you need to batch modify these three files. The for loop and sub() character replacement functions are mainly used. The idea is to first read the three file names below the test folder to the variables through the () function, and then use the for loop to batch modify the file name.
1. Modify the file extension
folder<-setwd('~/test') files<-(folder) for (f in files){ newname<-sub(".txt",'.xls',f) (f,newname) } dir()
Show results:
[1] "" "" ""
2. Delete the file extension
folder<-setwd('~/test') files<-(folder) for (f in files){ newname<-sub('.xls','',f) (f,newname) } dir()
Show results:
[1] "text1" "text2" "text3"
3. Add file extension
Here we use a regular expression, using '$' instead of the end of the character, and replacing the end of the character with '.doc'
folder<-setwd('~/test') files<-(folder) for (f in files){ newname<-sub('$','.doc',f) (f,newname) } dir()
Output result:
"" "" ""
4. Modify the characters in the file name
folder<-setwd('~/test') files<-(folder) for (f in files){ newname<-sub('xt','ab',f) #Replace the character xt in the original file with a character ab (f,newname) } dir()
Output result:
[1] "" "" ""
5. Delete the number in the file name
Modify the files in the experimental directory to, and use the "\\d" regular expression instead of the numbers in the file.
folder<-setwd('~/test') files<-(folder) for (f in files){ newname<-sub('\\d','',f) (f,newname) } dir()
Output result:
[1] "" "" ""
Reference article:
Language file directory operation/article/338
Language String Replacement /emanlee/p/
This is the end of this article about batch modifying file names in R language. For more related contents of batch modifying file names in R language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!