2016-03-15 70 views
1

我目前在我的分析中爲每個物種都有單獨的腳本,我想嘗試將它寫入一個腳本,我可以在開始時指定哪些物種/年份的數據等。我正在分析。 我想知道是否有可能在腳本的開頭部分設置某些對象,然後使用更通用的代碼來讀取這些文件。例如;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) 

回答

2

file.path是你正在尋找

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

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

從文檔「比paste(...)更快」,並以適當的文件路徑分隔符的系統

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) 
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) 
+0

感謝蒂姆工作的功能。我得到了錯誤 - 錯誤:「}」中的意外'}',所以我在()中加入了return –