Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 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 Reply

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

 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...