2015-07-06 102 views
3

我有一段代碼,它從文件夾中讀取具有特定擴展名的所有文件,每個數據集都保存爲具有默認名稱的數據幀。代碼工作正常,直到我把它變成一個函數。該函數運行良好,但沒有返回任何東西。我想問一下這個函數是否有返回所有數據幀的方法?保存多個數據幀並將它們從函數返回

功能如下:

library(devtools); install_github(BioStatMatt/sas7bdat.parso) 

ReadFiles <- function() 
    { 
    path <- "C:/Users/abc/Desktop/abc/test/" 
    files <- list.files(path=path, pattern="*.sas7bdat") 
    for(file in files) 
     { 
     perpos <- which(strsplit(file, "")[[1]]==".") 
     assign(
     gsub(" ","",substr(file, 1, perpos-1)), 
     read.sas7bdat.parso(paste(path,file,sep=""))) 
     } 
    } 

我會明白一些指導到我怎樣才能使此功能工作。

謝謝。

+0

,而不是調用的分配功能,不能你把數據幀中的向量,並返回從功能?目前查看代碼我沒有看到函數結尾處的返回語句。 – ColinMc

回答

6

你的函數確實沒有返回任何東西。要解決這個問題,您可以將在for循環中生成的數據框保存在列表中,然後返回包含所有數據框的結果列表。

從概念上講,它會是這個樣子:

ReadFiles <- function() 
{ 
    files <- # fetch the files 
    resultList <- vector("list",length(files)) 
    for(i in seq(1,length(files))) # process each file 
    { 
    file <- files[i] 
    resultList[[i]] <- # fetch your data(frame) 
    } 
    resultList # Return the result! 
} 

results <- readFiles() 
# You can now access your individual dataframes like this: 
dataFrame1 <- results[[1]] 
# Or merge them all together if you like: 
combinedDataFrame <- do.call("rbind",results) 
相關問題