'R: to move files based on file name

I am looking on a way to move files from one folder to another based on a grouping trait. Say that I have directories called fruit_apple/, fruit_orange/, fruit_lemon/. And a file that states the classification of each fruit like below.

classification <- matrix(c('apple', 'non-citrus', 'banana','non-citrus',  'lemon', 'citrus'), ncol=2, byrow=TRUE)
colnames(classification) <- c('fruit','class')

Is it possible to create a function that moves the directories from the source to an output directory by class? For instance, fruit_apple/ would be moved to non-citrus/fruit_apple.

Thanks in advance everyone!

r


Solution 1:[1]

I suggested in my comment, it it possible to do something like:

apply(classification, 1, function(x) file.copy(from = paste0("./", x[1], ".txt"), to = paste0("./", x[2], "/", x[1], ".txt")))

apply() with argument MARGIN = 1 operates by rows of classification. Then a custom function uses the information from the row (x) to feed the arguments of the function file.copy().

To make it easier, I have used a RStudio project so I could use relative path ./. Folders citrus and non-citrus were manually created before running the code.

Starting situation:

C:.
|   apple.txt
|   banana.txt
|   lemon.txt
|   starttree.txt
|   testR.Rproj
|   
+---citrus
\---non-citrus

End result:

C:.
|   apple.txt
|   banana.txt
|   lemon.txt
|   Resultant.txt
|   testR.Rproj
|   
+---citrus
|       lemon.txt
|       
\---non-citrus
        apple.txt
        banana.txt

If you want to also remove the files after copying them, you can add file.remove(paste0("./", x[1], ".txt")) to the custom function inside apply.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1