来自串联的R-project文件路径 [英] R-project filepath from concatenation

查看:85
本文介绍了来自串联的R-project文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过R教程。我一直在研究一个函数,函数的其中一个部分是引用一个参数并用它来定义一个目录来查找数据。它必须然后加载该数据。

现在有以下工作:

  getmonitor<  - 函数(id,目录){

csvfile< - 函数(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))

}

好。但我现在必须使用目录参数来定义必须从中读取csv文件的目录。我在这里尝试了各种各样的东西,无济于事。



目前,如果假定数据在工作目录中,代码就可以工作。我需要说去目录调用(目录),然后read.csv。

包含所有数据文件的目录称为specdata,参数因为目录是specdata。



我试过以下内容:

 <$ c $ (ID,目录){

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 )

}

但是我收到错误信息Error in! after:无效参数类型



我尝试了几个不同的东西,如果我剪切并粘贴所有代码,它可能比帮助更混乱。

什么是符合逻辑的方法?我是否正确第二?如果不是,我还应该起诉吗?我需要参数目录,然后加载该目录中的数据。

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

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

filepath< - file.path(directory,csvfile)

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

foo

}


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.

解决方案

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

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

  filepath <- file.path(directory, csvfile)

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

  foo

 }

这篇关于来自串联的R-project文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆