Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

function - R-project filepath from concatenation

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
getmonitor <- function(id, directory=getwd(), ...){

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

  filepath <- file.path(directory, csvfile)

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

  foo

 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...