Created
May 17, 2016 07:53
-
-
Save talegari/cab4f93ee37225e0417528cc20df025b to your computer and use it in GitHub Desktop.
[R] Read files with specific extensions in the directory as dataframes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# read_dir | |
# description | |
# | |
# read files with specific extensions in the directory as dataframes | |
# args | |
# | |
# directory : directory should not end with "\" | |
# extensions : extensions of the files to be selected as a character | |
# vector. Default: c("csv") | |
# read_function : function as a name or as a string. Deafult: "read.csv" | |
# env : environment where the dataframes are loaded to | |
# Default: parent.frame() | |
# ... : arguments passed to read_function | |
# Dependencies | |
# | |
# >= R 3.0 | |
# assertthat | |
# tools | |
# author | |
# Srikanth KS (talegari) | |
# gist.github.com/talegari | |
read_dir = function(directory | |
, extensions = c("csv") | |
, read_function = "read.csv" | |
, env = parent.frame() | |
, ...){ | |
stopifnot(require("assertthat")) | |
assert_that(require("tools")) | |
assert_that(file_test("-d", directory)) | |
assert_that(is.readable(directory)) | |
assert_that(class(extensions) == "character") | |
assert_that(is.function(match.fun(read_function))) | |
args = list(...) | |
filenames = list_files_with_exts(directory, extensions) | |
for(filename in filenames){ | |
assign(file_path_sans_ext(basename(filename)) | |
, do.call(read_function | |
, c(filename, args) | |
) | |
, envir = env) | |
} | |
return(invisible(TRUE)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment