Doug Fir
Doug Fir

Reputation: 21282

Objects not found when reading in a function via R Studio

When I run my code via R-Studio I'm told I have an unexpected curly brace.

I have four: two to open/close the function and two for the for loop. I'm then told many of the variables are not found: Unexpected "for", "directory" not found, "basedf" not found. It's as if nothing from my function is recognized.

I tried cutting and pasting the function directly into the console but with similar errors.

Is my function flawed, or is something else the issue?

pollutantmean <- function(directory, pollutant, id = 1:332) {
    files <- list.files(directory)
    subsetFiles <- files[id]
    basedf <- data.frame(Date = as.Date(character(),
            sulfate = numeric(),
            nitrate = numeric(),
            ID = numeric())
    for (i in subsetFiles) {
        filepaths <- paste(directory,"/",i, sep='')
        basedf <- rbind(basedf, read.csv(filepaths))
    }
    good <- complete.cases(basedf)
    data2 <- basedf[good,pollutant]
    mean(data2)
}

Upvotes: 0

Views: 2141

Answers (2)

flamenco
flamenco

Reputation: 2840

Actually, it should be as:

          basedf <- data.frame(Date = as.Date(character()),
                                              sulfate = numeric(),
                                              nitrate = numeric(),
                                              ID = numeric()) 

There is missing parenthesis but is the closing one from as.Date().

It seems that you are working on the assignment from Coursera. You might want to add the format for as.Date().

 R:> basedf <- data.frame(Date = as.Date(character(), format='%Y/%m/%d'),
                       sulfate = numeric(),
                       nitrate = numeric(),
                       ID = numeric())

 R:> basedf
 [1] Date    sulfate nitrate ID     
 <0 rows> (or 0-length row.names)

Upvotes: 1

Csislander
Csislander

Reputation: 2160

You are simply missing a bracket in basedf:

basedf <- data.frame(Date = as.Date(character(),
                     sulfate = numeric(),
                     nitrate = numeric(),
                     ID = numeric()))

Then everything should work fine.

Alternatively, you could have the bracket at the end of as.Date as stated by flamenco, but your function will still compile either way. It depends on what the purpose of your function is.

Upvotes: 1

Related Questions