Reputation: 1023
I currently have individual scripts for each species in my analysis, I'd like to try and get it into one script where I can specify at the beginning which species/year of data etc. I am analysing. I'd like to know if it is possible to instead set at the beginning of the script certain objects and then have more generic code to read in the files. for example;
existing code
ABR <- read.csv("Y:/Pelagic Work/FIN Data/2015/HOM/Abroad.csv",sep=",",skip = 2,header=T)
SCO <- read.csv("Y:/Pelagic Work/FIN Data/2015/HOM/Scotland.csv",sep=",",skip = 2,header=T)
I'd like something like;
Year <- 2015
Species <- HOM
ABR <- read.csv("Y:/Pelagic Work/FIN Data/Year/Species/Abroad.csv",sep=",",skip = 2,header=T)
SCO <- read.csv("Y:/Pelagic Work/FIN Data/Year/Species/Scotland.csv",sep=",",skip = 2,header=T)
Upvotes: 1
Views: 67
Reputation: 522762
I defined a helper function getFileName()
which does the heavy lifting of building the path of the file you want to read.
getFileName <- function(root, year, species, file) {
return (paste(root, year, species, file, sep="/"))
}
root <- "Y:/Pelagic Work/FIN Data"
year <- "2015"
species <- "HOM"
file <- "Abroad.csv"
fileName <- getFileName(root, year, species, file, sep="/")
ABR <- read.csv(fileName,sep=",",skip = 2,header=T)
Upvotes: 2
Reputation: 115505
file.path
is the function for which you are looking
root <- "Y:/Pelagic Work/FIN Data"
year <- "2015"
species <- "HOM"
file <- "Abroad.csv"
ABR <- file.path(root, year, species, file)
From the docs "Faster than paste(...)
" and works with the appropriate filepath separator for the system
Upvotes: 2
Reputation: 24280
You can use sprintf
for this:
Year <- 2015
Species <- HOM
abroad.path <- sprintf("Y:/Pelagic Work/FIN Data/%s/%s/Abroad.csv", Year, Species)
scotland.path <- sprintf("Y:/Pelagic Work/FIN Data/%s/%s/Scotland.csv", Year, Species)
ABR <- read.csv(abroad.path, sep=",", skip=2, header=T)
SCO <- read.csv(scotland.path, sep=",", skip=2, header=T)
Upvotes: 2