szmple
szmple

Reputation: 455

Extract files from multiple folders in R

I have a directory full of folders Like this, and in each of those folders is a .tsv file I need to extract to a different directory (so that all the files in the folders are together in one folder)

My idea was to write a for loop in R which would get a list with all files in root directory, open those, copy the .tsv file to the new location

it would look something like this:

Files <- list.files("directory")
directory1 <- "root directory"
directory2 <- "place they need to go"
for (i in files){
file.copy(from = directory1,
          to = directory2)}

this however does not work.

Upvotes: 0

Views: 1627

Answers (2)

tabumis
tabumis

Reputation: 106

Though it may be late now, the solution is in specifying the recursive= and full.names= arguments in the list.files() function.

After that you can copy the files without using loops:

Files <- list.files("directory", recursive=TRUE, full.names=TRUE) 
file.copy(from=Files, to="new_directory")

Upvotes: 2

MrFlick
MrFlick

Reputation: 206401

You're not using i in the loop so that's part of the problem. Try

for (i in files){
  file.copy(from = file.path(directory1, i),
            to = file.path(directory2, i))
}

Upvotes: 1

Related Questions