Home > Software design >  Paste a file path onto the beginning of each element of a character list of file names in R
Paste a file path onto the beginning of each element of a character list of file names in R

Time:12-13

I have a character vector of file names from a folder that I need to transform into individual file paths so each element of the list has the full file path that can then be manipulated using xmlParse. The character vector was created using the following example code:

files <- list.files(path = "C:\\Users\\Documents\\XML")
class(files)
[1] "character"

#output looks like this (there are actually 60  files - condensed here for example)
> files
 [1] "file1.xml" "file2.xml"
 [3] "file3.xml" "file4.xml"
 [5] "file5.xml" "file6.xml"

I need to somehow go through this vector and add the beginning part of the path for each file name so they can be accessed in a loop later on. I've tried various combinations of lapply, paste0, sapply paste but keep getting errors in the code.

Here are a couple examples of tries and errors:

home.path <- ("C:\\Users\\Documents\\XML")
filepaths <- lapply(files, paste0(home.path))
> filepaths <- lapply(files, paste0(home.path))
Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'C:\Users\Documents\XML' of mode 'function' was not found

filepaths <- sapply(files, paste0(home.path, var, sep = ""))
> filepaths <- sapply(files, paste0(home.path, var, sep = ""))
Error in paste0(home.path, var, sep = "") : 
  cannot coerce type 'closure' to vector of type 'character'

If this was working the way I intended, it should return this:

>filepaths
[1] "C:\\Users\\Documents\\XML\\file1.xml"
[2] "C:\\Users\\Documents\\XML\\file2.xml"
[3] "C:\\Users\\Documents\\XML\\file3.xml"
...

CodePudding user response:

You can simply use paste0() directly on the character vector (there's no need for an explicit loop), like so:

filenames <- c("a.txt", "b.txt", "c.txt")
paste0("prefix/", filenames)
#> [1] "prefix/a.txt" "prefix/b.txt" "prefix/c.txt"

R seldom operates on single bits of data; most operations apply to vectors of data.

CodePudding user response:

If you want to loop through each file (for editing or combining):

for (file in files) {
   print(paste0("C:\\Users\\Documents\\XML\\", file))
}
  • Related