我想了解“返回”在我为计算智能手机价格平均值而创建的函数中的位置。
以下是我的数据集“智能手机”中的所有价格
smartphones$Price
[1] 4688 5088 5588 6388 4398 5998 7498 3298 2898 4498 2598 5998 3998 5498 2998
4298 5598 2698 4998 3598下面是我创建的函数:
mean.kevin <- function(dataVector)
{
total = 0;
n = length(dataVector);
for (v in dataVector)
{
total = total + v
}
return (total/n)
}
mean.kevin(smartphones$Price)通过将返回放置在"for“循环之外,将返回正确的答案,如下所示:
> mean.kevin(smartphones$Price)
[1] 4631但是,如果我将返回放在这样的"for“循环中:
mean.kevin <- function(dataVector)
{
total = 0;
n = length(dataVector);
for (v in dataVector)
{
total = total + v
return (total/n)
}
}
mean.kevin(smartphones$Price)当我执行代码时,会给出错误的答案:
> mean.kevin(smartphones$Price)
[1] 234.4我不理解在Rstudio中将返回放在for循环内部或外部之间的区别。谢谢。
发布于 2018-02-07 09:12:58
在内部,您打破for循环,在第一个循环中退出迭代。
这里有一个例子:
#Breaking the forloop function
f1<-function() {
for (i in 1:20)
{
return(i)
}
}
#Right use of return function
f2<-function() {
for (i in 1:20)
{
}
return(i)
}
f1()
[1] 1
f2()
[1] 20https://stackoverflow.com/questions/48659770
复制相似问题