Copy a directory in R

The idea of this post it to create a recursive function in R to make a copy of a directory. So the schema will be the following one:

GeneralFunction <- function(from, to) {
    SpecificFunction <- function(from, to) {
        # Create the directory 'to'
        # Get the files in 'from'
        # Get the directories in 'from'
        # Copy the files from 'from' to 'to'
        # foreach directory in from:
        #    SpecificFunction(from + directory, to + directory) 
    }

    # Clean arguments 'from' and 'to'
    SpecificFunction(from, to)
}

The R code to implement that is the following:

CopyDirectory <- function(from, to, overwrite = TRUE, verbose = FALSE) {

    show <- function(...) {
        if (verbose) {
            message("[ CopyDirectory ]: ", ... )
        }
    }

    iCopyDirectory <- function(from, to, overwrite = TRUE, verbose = FALSE) {
        show("Creating new '", to, "'.")
        dir.create(to, showWarnings=FALSE)

        # Get and prepare the content to be copies
        from.dirs <- basename(list.dirs(from))
        from.dirs <- from.dirs[from.dirs != basename(from)]

        from.files <- list.files(from)
        from.files <- from.files[!(from.files %in% from.dirs)]

        # Copy files in this level
        d <- sapply(from.files, function(x){
                complete.from <- file.path(from, x, fsep=.Platform$file.sep)
                complete.to <- file.path(to, x, fsep=.Platform$file.sep)
                show("Coping file '", complete.from, "' to '",
                    complete.to, "'.")
                file.copy(complete.from, complete.to)
            }
        )
        rm("d")

        # Look for deeper levels and apply the same function
        d <- sapply(from.dirs, function(x) {
                complete.from <- file.path(from, x, fsep=.Platform$file.sep)
                complete.to <- file.path(to, x, fsep=.Platform$file.sep)
                iCopyDirectory(complete.from, complete.to, overwrite=FALSE,
                    verbose=verbose)
            }
        )
        rm("d")
    }

    # Clean 'from' and 'to' content
    from <- basename(from)
    to <- basename(to)

    # Remove first level
    if (overwrite) {
        show("Removing '", to, "'.")
        unlink(to, recursive = TRUE, force=TRUE)
    }

    # Start copying
    iCopyDirectory(from, to)
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: