Skip to content

Instantly share code, notes, and snippets.

@zkamvar
Last active Dec 16, 2015
Embed
What would you like to do?
Function from the package [poppr](https://github.com/poppr/poppr) that serves as a wrapper for `file.choose()`, `file.path()`, and `list.files()`. It will allow the user to grab multiple files for import into R with their gui.
#==============================================================================#
# Usage:
# x <- getfile() # for a single file.
# x <- getfile(multi = TRUE) # for multiple files
# x <- getfile(multi = TRUE, pattern = "^.+?csv$") # grabs all *.csv files.
# setwd(x$path)
# read.csv(x$files)
#==============================================================================#
getfile <- function(multi=FALSE, pattern=NULL, combine=TRUE){
# the default option is to grab a single file in the directory. If multFile is
# set to TRUE, it will grab all the files in the directory corresponding to any
# pattern that is set. If there is no pattern, all files will be grabbed.
if (multi==TRUE){
# this sets the path variable that the user can use to set the path
# to the files with setwd(x$path), where x is the datastructure
# this function dumped into.
pathandfile <- file.path(file.choose())
path <- dirname(pathandfile)
if (!is.null(pattern)){
pat <- pattern
x <- list.files(path, pattern=pat)
}
else {
x <- list.files(path)
}
}
else {
# if the user chooses to analyze only one file, a pattern is not needed
pathandfile <- file.path(file.choose())
path <- dirname(pathandfile)
x <- basename(pathandfile)
}
if(combine == TRUE){
x <- paste(path, x, sep="/")
}
filepath <- list(files=x, path=path)
return(filepath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment