6
votes

I'm working through an R tutorial. I've been working on a function and one of the parts of the function is to take an argument and use it to define a directory in which to find data. It must then load that data.

As it stands the following works:

getmonitor <- function(id, directory){

csvfile <- function(id) {
    if (id < 10) { 
        paste0(0,0,id,".csv")
    } else if (id < 100) {
        paste0(0,id,".csv")
    } else paste0(id,".csv")
}

foo <- read.csv(csvfile(id))

}

Fine. But I now have to use the "directory" parameter to define the directory where the csv file must be read from. I've tried various things here to no avail.

Currently, the code works if the assumption is that the data are in the working directory. I need to say "go to the directory called (directory) and then read.csv.

The directory with all of the data files is called "specdata" and the parameter for directory is thus "specdata".

I tried the following:

getmonitor <- function(id, directory){

  csvfile <- function(id) {
      if (id < 10) { 
          paste0(0,0,id,".csv")
      } else if (id < 100) {
          paste0(0,id,".csv")
      } else paste0(id,".csv")
  }

  filepath <- append(directory,"/",csvfile(id))

  foo <- read.csv(filepath)

 }

But then I received an error message "Error in !after : invalid argument type "

I have tried a few various things and if I cut and paste all the code it would probably be more messy than help.

What would be a logical way to do this? Am I on the right track with append? What else should I sue if not? I need to take the parameter "directory" and then load data from that directory.

1
You want paste(directory, csvfile(id), sep="/") instead of append which does something completely different.Matthew Lundberg
You appear to be using append without having read ?append or testing the examples at the bottom of the documentation to see what it does.joran
also, instead of your entire csvfile function you can use sprintf('%03d', id).Justin

1 Answers

7
votes
getmonitor <- function(id, directory=getwd(), ...){

  csvfile <- sprintf("%03d.csv", id)

  filepath <- file.path(directory, csvfile)

  foo <- read.csv(filepath, ...)

  foo

 }