2017-04-04 180 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

相关问题