use index number to name file in r

To use an index number to name a file in R, you can concatenate a string that includes the index number and the file extension. You can do this by using paste0() function, which combines the inputs into a single string without any separator. Here's an example:

main.r
# create a vector of file names
file_names <- c("file1.txt", "file2.txt", "file3.txt")

# loop through the file names and rename them with index number
for(i in seq_along(file_names)) {

  # get the new file name with index
  new_name <- paste0("file_", i, ".txt")
  
  # rename the file
  file.rename(file_names[i], new_name)
}
329 chars
13 lines

In the above example, we first create a vector of file names file_names with the original file names. We then loop through the file names using seq_along() function to access the index number. We use paste0() function to concatenate the string "file_" with the index number i and the file extension ".txt" to create the new file name. Finally, we use file.rename() function to rename the file with the new name.

gistlibby LogSnag