0

i am trying to do an assignment from the R programming course at coursera, but my function does not work, and i have no idea why. i see no problems with it, and Rstudio reports no errors as well.

this is the function

pollutantmean<- function(id, polutant) {

    files<- list.files("specdata", full.names = T)
    table<-data.frame()
    for(id in head(id,n=1):tail(id,n=1)){
            loc<-read.csv(files[id])
            table<- rbind(table,loc)
    }     
    if(polutant=="nitrate") {
            mean(table[,"nitrate"],na.rm = T )
    }
    if(polutant=="sulfate") {
            mean(table[,"sulfate"],na.rm = T )
    }
}

but when i try to run

pollutantmean(8,"nitrate")

or anything similar, nothing happens. i see no output or change in the global environment.

but when i run the statements without putting them in the function, line for line, it works

if i do this:

 id<- 5

then

  polutant<-"nitrate" 

then

files<- list.files("specdata", full.names = T)

then

table<-data.frame()

then

 for(id in head(id,n=1):tail(id,n=1)){
        loc<-read.csv(files[id])
        table<- rbind(table,loc)
}

(here, i would already see table and doc merging in the global environment)

if(polutant=="nitrate") {
        mean(table[,"nitrate"],na.rm = T )
}

here, i would get an answer that matches the example output provided with the asignment.

joran
  • 169,992
  • 32
  • 429
  • 468
  • 3
    Did you intend to `print()` or `return()` something from your function? – cory Mar 24 '16 at 20:20
  • 2
    This would have been more appropriately posted to the website where the Coursera related questions are supposed to be directed. You don't appear to have yet grasped the fact that the results of function need to be assigned to a symbol. Changing a value inside the function does nothing to objects in the global environment. Also looks that you are mispledding "pollutant". Don't you just hate yourself when you mispled something? – IRTFM Mar 24 '16 at 20:21
  • Agree with @cory, you seem to miss something to `return`. – Stereo Mar 24 '16 at 20:21
  • @cory , yes, it seems that way. when i added it, it worked like i intended. but why is it needed here, and not in something like `f1 <- function(x, y) { x+y }` ? In some examples of functions, i did not see `return()` and in some i did. how do i know if it should be used? – lightvader Mar 24 '16 at 20:48
  • @lightvader Your personal google service has delivered... http://stackoverflow.com/questions/11738823/explicitly-calling-return-in-a-function-or-not – cory Mar 24 '16 at 21:00

0 Answers0