简体   繁体   中英

Position of return in a function in R

I would like to understand the position of "return" in the function which I created to calculate the mean of smartphone prices.

Here are all the prices in my dataset "smartphones"

smartphones$Price
[1] 4688 5088 5588 6388 4398 5998 7498 3298 2898 4498 2598 5998 3998 5498 2998 
4298 5598 2698 4998 3598

Here is the function that I've created:

mean.kevin <- function(dataVector)
{
   total = 0;
   n = length(dataVector);
   for (v in dataVector)
 {
   total = total + v

  } 
     return (total/n)
   }

mean.kevin(smartphones$Price)

By placing the return outside of the "for" loop will return the correct answer as shown below:

> mean.kevin(smartphones$Price)
[1] 4631

However, if I placed the return inside the "for" loop as such:

mean.kevin <- function(dataVector)
{
  total = 0;
  n = length(dataVector);
  for (v in dataVector)
 {
  total = total + v
  return (total/n)
  } 

 }

mean.kevin(smartphones$Price)

When I execute the code, the wrong answer will be given:

> mean.kevin(smartphones$Price)
[1] 234.4

I do not understand the difference between putting the return inside or outside the for loop in Rstudio. Thank you.

Inside you break the for loop and go out of the iteration at the first loop.

Here an example:

#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] 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM