r预先指定文件路径的一部分

时间:2016-03-15 09:49:16

标签: r

我目前在我的分析中为每个物种编写了单独的脚本,我想尝试将其放入一个脚本中,我可以在开始时指定我正在分析的物种/年数据等。 我想知道是否可以在脚本的开头设置某些对象,然后在文件中读取更多通用代码。例如;

现有代码

ABR <- read.csv("Y:/Pelagic Work/FIN Data/2015/HOM/Abroad.csv",sep=",",skip = 2,header=T)
SCO <- read.csv("Y:/Pelagic Work/FIN Data/2015/HOM/Scotland.csv",sep=",",skip = 2,header=T)

我喜欢类似的东西;

Year <- 2015 
Species <- HOM

ABR <- read.csv("Y:/Pelagic Work/FIN Data/Year/Species/Abroad.csv",sep=",",skip = 2,header=T)
SCO <- read.csv("Y:/Pelagic Work/FIN Data/Year/Species/Scotland.csv",sep=",",skip = 2,header=T)

3 个答案:

答案 0 :(得分:2)

您可以使用sprintf

Year <- 2015
Species <- HOM

abroad.path <- sprintf("Y:/Pelagic Work/FIN Data/%s/%s/Abroad.csv", Year, Species)
scotland.path <- sprintf("Y:/Pelagic Work/FIN Data/%s/%s/Scotland.csv", Year, Species)

ABR <- read.csv(abroad.path, sep=",", skip=2, header=T)
SCO <- read.csv(scotland.path, sep=",", skip=2, header=T)

答案 1 :(得分:2)

我定义了一个辅助函数getFileName(),它可以帮助您构建想要读取的文件的路径。

getFileName <- function(root, year, species, file) {
    return (paste(root, year, species, file, sep="/"))
}

root <- "Y:/Pelagic Work/FIN Data"
year <- "2015"
species <- "HOM"
file <- "Abroad.csv"

fileName <- getFileName(root, year, species, file, sep="/")

ABR <- read.csv(fileName,sep=",",skip = 2,header=T)

答案 2 :(得分:2)

file.path是您正在寻找的功能

root <- "Y:/Pelagic Work/FIN Data"
year <- "2015"
species <- "HOM"

file <- "Abroad.csv"
ABR <- file.path(root, year, species, file)

来自文档&#34;快于paste(...)&#34;并使用适当的系统文件路径分隔符