Manipulating Files in R: Renaming

R is not just for statistics, it provides many other functions that can make life much easier. In this post I provide a solution for renaming different files.

Problem

I wanted to remove the substrings ‘TextGrid’ and ‘Sound’ from a list of Praat generated filesnames. The filenames had the following form:

TextGrid_Soundname.TextGrid
Sound_Soundname.wav

Solution

#Using R to Replace FileNames

path_origin <- “C:\\Sounds\\”

files <- list.files(path_origin) # Get a list of files in R.

xfiles <- paste(path_origin, files, sep = “”) # add the full path, (I removed the space inserted between two concatenated strings by using sep=””)

sapply(path_origin, function(path_origin) # sapply(list, function, …, simplify)

{

file.rename(xfiles, sub(“Sound “, “”, xfiles)) # renaming the files by using the sub() function, the first argument xfiles is the list of files, the second is the new name for each file. It simply removes “Sound “.

}

)

You may use this solution to change part of the filename or the file extension by choosing the appropriate sub() parameters.

! Be careful with the choice of the path and the sub() parameters; if you choose the wrong parameters then you may get unexpected results.

More Information

http://stat.ethz.ch/R-manual/R-patched/library/base/html/files.html

R Library: Advanced functions

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s