1

I'm new to R, and I'm having trouble figuring out how to replace the FOR loop in the function below. The function estimates a population mean. Any help at all would be much appreciated. Thank you!

 myFunc<- function(){


myFRAME <- read.csv(file="2008short.csv",head=TRUE,sep=",")

meanTotal <- 0

for(i in 1:100)
{

mySample <- sample(myFRAME$TaxiIn, 100, replace = TRUE)

tempMean <- mean(mySample)

meanTotal <- meanTotal + tempMean


}

cat("Estimated Mean: ", meanTotal/100, "\n") #print result

}
unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613

2 Answers2

5

As Rob suggests your loop is unnecessary, but in the spirit of the question the 'replicate()' function can directly replace your for loop. Like so:

   myFunc <- function(){
      myFRAME <- read.csv(file="2008short.csv",head=TRUE,sep=",")
      meanTotal <- <- mean(replicate(100,mean(sample(myFRAME$TaxiIn,100,T))))
      cat("Estimated Mean: ", meanTotal, "\n")
    }
wkmor1
  • 6,916
  • 3
  • 30
  • 23
2

Your code takes the mean of 100 sample means, each based on a sample of 100 observations. This is equivalent to taking the mean of 10,000 observations. So the following will do the same thing:

myFunc <- function(){
  myFRAME <- read.csv(file="2008short.csv",head=TRUE,sep=",")
  meanTotal <- sample(myFRAME@TaxiIn,10000,replace=TRUE)
  cat("Estimated Mean: ", meanTotal, "\n")
}
Rob Hyndman
  • 28,598
  • 7
  • 67
  • 82