Elan
Elan

Reputation: 549

Basic R malfunction

R beginner. Why doesn't this code return the number 3?

my_mean <- function(my_vector){
  sum(my_vector)/length(my_vector)
  my_mean
}
my_vector <- c(1, 3, 5)
my_mean

I'm not allowed to use mean(). Thanks

Upvotes: 0

Views: 104

Answers (2)

Elan
Elan

Reputation: 549

Problem solved. I made a mistake in the way I called the function. The call should be:

my_mean(c(1,3,5))

not:

my_vector <- c(1, 3, 5)
my_mean

Upvotes: 0

Hong Ooi
Hong Ooi

Reputation: 57697

Returning a value by assigning to the function name is Visual Basic syntax. To my knowledge, no other language uses this technique.

If you want to return a value in R, use the return() statement:

mymean <- function(x)
{
    val <- sum(x)/length(x)
    return(val)
}

But there's a shorter way to achieve the same result. If R reaches the end of a function without an explicit return, it will return the value of the last expression it found.

mymean <- function(x)
{
    val <- sum(x)/length(x)
    val                      # value of last expression is returned
}

But this can be shortened further. The variable val is only used once, as the last statement in the function. So we could omit it entirely, and just return the computed value itself without storing it in a variable first:

mymean <- function(x)
{
    sum(x)/length(x)
}

Upvotes: 3

Related Questions