2017-04-04 252 views
0

一直在這個幾個小時左右。我在R上的第一個問題嘗試創建一個包含循環的函數。該函數接受用戶提交的一個向量,如污染物平均值(4:6),然後加載一堆csv文件(在提到的目錄中)並綁定它們。奇怪的是(對我來說)是,如果我分配變量id,然後在不使用函數的情況下運行循環,它就可以工作!當我把它放在一個函數中,以便用戶可以提供id向量時,它什麼都不做。有人可以幫忙嗎?謝謝!!!循環在函數外工作,但在函數中不工作。

pollutantmean<-function(id=1:332) 
     { 
     #read files 
     allfiles<-data.frame() 
     id<-str_pad(id,3,pad = "0") 
     direct<-"/Users/ped/Documents/LearningR/" 
       for (i in id) { 
       path<-paste(direct,"/",i,".csv",sep="") 
       file<-read.csv(path) 
       allfiles<-rbind(allfiles,file) 
          } 
     } 
+3

您的函數缺少返回值。 – Roland

回答

0

您的函數缺少返回值。 (@Roland)

pollutantmean<-function(id=1:332) { 
    #read files 
    allfiles<-data.frame() 
    id<-str_pad(id,3,pad = "0") 
    direct<-"/Users/ped/Documents/LearningR/" 
      for (i in id) { 
      path<-paste(direct,"/",i,".csv",sep="") 
      file<-read.csv(path) 
      allfiles<-rbind(allfiles,file) 
         } 
return(allfiles) 
    } 

編輯: 你的錯誤是,你想從功能得到了什麼你沒有在你的函數中指定。在R中,你可以在函數內部創建對象(你可以將它想象成不同的環境),然後指定你希望它返回的對象。

我的評論關於接受我的答案,我的意思是this:(...爲了將答案標記爲已接受,請單擊答案旁邊的複選標記以將其從灰色變爲填充...)。

+0

非常感謝您的快速回復!這很有趣,因爲R打印文件的開始(不要認爲它打印整個文件,看起來很短,可能只是循環的第一次迭代),但不會「構建」allfiles文件。 – Pepe

+0

@Pepe所以我的回答有幫助?我沒有從你的評論中得到它。如果這樣考慮接受它.. – minem

+0

它絕對有幫助!但我也非常有興趣瞭解我做錯了什麼,以便我可以學習。非常感謝您的時間! – Pepe

0

考慮甚至lapplydo.call這不會需要return是函數最後一行:

pollutantmean <- function(id=1:332) {  
    id <- str_pad(id,3,pad = "0") 
    direct_files <- paste0("/Users/ped/Documents/LearningR/", id, ".csv") 

    # READ FILES INTO LIST AND ROW BIND 
    allfiles <- do.call(rbind, lapply(direct_files, read.csv)) 
} 
+0

非常感謝!我會嘗試的。想知道爲什麼我做的不起作用。我認爲它的參數「id」被傳遞給函數的方式。但是可以弄清究竟是什麼問題。 – Pepe

0

好吧,我知道了。我期待的是構建的文件實際上已經創建並顯示在R的環境中。但是由於某些原因,他們沒有。但是R仍然會做所有的計算。謝謝你的回覆!

pollutantmean<-function(directory,pollutant,id) 
{ 
    #read files 
    allfiles<-data.frame() 
    id2<-str_pad(id,3,pad = "0") 
    direct<-paste("/Users/pedroalbuquerque/Documents/Learning R/",directory,sep="") 
    for (i in id2) { 
    path<-paste(direct,"/",i,".csv",sep="") 
    file<-read.csv(path) 
    allfiles<-rbind(allfiles,file) 
    } 
#averaging polutants 
mean(allfiles[,pollutant],na.rm = TRUE) 
} 

pollutantmean("specdata","nitrate",23:35) 
+0

對不起,但您是否注意到我對答案(http://stackoverflow.com/a/43209515/7063375)所做的更改? – minem

相關問題