Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using R to copy files

Tags:

file

copy

r

As part of a larger task performed in R run under windows, I would like to copy selected files between directories. Is it possible to give within R a command like cp patha/filea*.csv pathb (notice the wildcard, for extra spice)?

like image 488
gappy Avatar asked Mar 05 '10 04:03

gappy


People also ask

How do I copy a folder in R?

copy() function as shown in the following R syntax. Within the file. copy function, we have to specify the directory path and file names of the first folder from which we want to copy the files, as well as the directory path and file names of the second folder to which we want to copy the files.

How do I move files in RStudio?

Simply check the boxes next to the filenames of the files you like to move, then click Move... and select the folder where you want to move them to. The folder I want to move it to is another rstudio. cloud project.


2 Answers

I don't think there is a direct way (shy of shelling-out), but something like the following usually works for me.

flist <- list.files("patha", "^filea.+[.]csv$", full.names = TRUE) file.copy(flist, "pathb") 

Notes:

  • I purposely decomposed in two steps, they can be combined.
  • See the regular expression: R uses true regex, and also separates the file pattern from the path, in two separate arguments.
  • note the ^ and $ (beg/end of string) in the regex -- this is a common gotcha, as these are implicit to wildcard-type patterns, but required with regexes (lest some file names which match the wildcard pattern but also start and/or end with additional text be selected as well).
  • In the Windows world, people will typically add the ignore.case = TRUE argument to list.files, in order to emulate the fact that directory searches are case insensitive with this OS.
  • R's glob2rx() function provides a convenient way to convert wildcard patterns to regular expressions. For example fpattern = glob2rx('filea*.csv') returns a different but equivalent regex.
like image 63
mjv Avatar answered Sep 29 '22 12:09

mjv


You can

  • use system() to fire off a command as if it was on shell, incl globbing
  • use list.files() aka dir() to do the globbing / reg.exp matching yourself and the copy the files individually
  • use file.copy on individual files as shown in mjv's answer
like image 37
Dirk Eddelbuettel Avatar answered Sep 29 '22 12:09

Dirk Eddelbuettel