繁体   English   中英

如何在不更改R中的工作目录的情况下访问子文件夹中的指定文件?

[英]How to access to specify file in subfolder without change working directory In R?

在 R 中,我想访问子文件夹中的某个文件。 但我不想更改工作目录然后移回。 它失去了时间和漫长。

例如,我在/home/phuong文件夹上工作。 这是 phuong 的树结构。

phuong-> data1, data2, data3.
data1-> abc.csv, def.csv, script1.R
data2-> bond.csv, option.csv, pricing.R
data3->.....

所以我想在 abc.csv、def.csv 中加载数据并在pricing.R 中运行代码。

所以如果使用代码setwd ,它会让我失去很多时间并且看起来代码很愚蠢,就像这样:

setwd("/home/phuong/data1" );

read.csv("abc.csv");
read.csv("def.csv");
setwd("/home/phuong/data2" );
source("pricing.R")

我失去了很多次从文件夹移动到另一个文件夹,但它们都在同一个文件夹home/phuong/ 所以我需要一些方法来访问子文件夹中的任何文件而无需setwd命令。 请帮助我,谢谢。

假设您的工作目录是/home/hermie并且您想从当前 WD 下的目录加载.csv文件(比如/home/hermie/data ),您可以简单地执行以下操作:

setwd('/home/hermie')
myData <- read.csv('./data/myCsvFile.csv')

当然,您也可以在目录树中“向上”导航。 假设您要在 Bob 的主目录 ( /home/bob ) 中加载一个文件。 你可以这样做:

setwd('/home/hermie')
data_from_bob <- read.csv('../bob/otherDataFile.csv') # Of course, this will work
                                                      # only if you can read
                                                      # files from that directory

希望这可以帮助。


更新

不知何故,我认为您希望有人为您编写解决方案……我建议这样做:

> setwd('/home/phuong')
> data_abc <- read.csv('./data1/abc.csv')
> data_def <- read.csv('./data1/def.csv')
> source('./data2/pricing.R')

写这个真的有那么难吗? 如果你在每一步都改变了你的 WD,你将不得不写更多。

而且,关于我对符号链接的建议,在您的 bash 终端上,您可以执行以下操作:

$ cd /home/phuong
$ ln -s ./data1/abc.csv data1_abc.csv
$ ln -s ./data1/def.csv data1_def.csv
$ ln -s ./data2/pricing.R pricing.R

然后,从 R:

> setwd('/home/phuong')
> data_abc <- read.csv('data_abc.csv')
> data_def <- read.csv('data_def.csv')
> source('pricing.R')

如果我了解您的要求,您可以使用 Hadley 在Advanced R 中所说的闭包:

## Make a function that takes a path and another function
## and returns that same function with the path pre-progammed in
pathit <- function(FUN, path){
    function(file, ...){
        FUN(file=file.path(path, file), ...)
    }
}

## generate new functions that have the path pre-programmed in
read.csv2b <- pathit(read.csv, "home/phuong/data1")
source2 <- pathit(source, "home/phuong/data2")


read.csv2b("abc.csv")
read.csv2b("def.csv")
source2("pricing.R")

如果你有很多东西要读,这可能是值得的,否则为什么不提供实际功能的完整路径呢? 如果这不是你所追求的,那对我来说仍然是一次有趣的学习经历:-)

对我来说,学习导航文件夹最直观的方法是使用list.files("../") 您将看到您需要从当前位置导航到上游或下游的程度:)

我不知道这是否是您要查找的内容,但是我在特定 github 文件夹中有一个文件库,当我在新分支中初始化项目时,我会使用该文件夹,并且我在网上找到了一个解决方案,如下所示:

setwd("~/repos/library/all_the_things")
library_files <- list.files()
sapply(library_files, source)

这很好,除了现在我在一个目录中启动每个文件,我不想保存图等,所以我意识到它需要的是:

library_files <- list.files("~/repos/library/all_the_things", full.name=T)
sapply(library_files, source)

现在它可以在不更改目录的情况下运行它们。

我刚刚发现了here包。 我将它用于我正在从事的项目 与目前提到的其他选项相比,它提供了一种更简洁的引用嵌套文件夹的方法。 举个例子:

install.packages('here')
library('here')
here::i_am("pricing.R")
read.csv(here("data1/abc.csv"));
read.csv(here("data1/def.csv"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM