替换R函数中的循环 [英] Replace Loops in R function
本文介绍了替换R函数中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是R的新手,我在弄清楚如何替换下面函数中的FOR循环时遇到麻烦.该函数估计总体平均值.任何帮助将不胜感激.谢谢!
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
}
推荐答案
正如罗布(Rob)所建议的那样,您的循环是不必要的,但从本质上讲,"replicate()" 函数可以直接替换您的for循环.像这样:
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")
}
这篇关于替换R函数中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文