stevec
stevec

Reputation: 52208

Unexpected behaviour of function used in conjunction with lapply/sapply?

This

mult_six <- function(x) {
  y <- x * 6
}

mult_six(7)

returns nothing (as expected), and y is not globally assigned (also as exptected, since assignment takes place in the scope of the function, not in the parent environment - so y returns Error: object 'y' not found - completely normal)

But

sapply(c(1,2,3), mult_six)

returns

[1]  6 12 18

(and lapply() returns the list equivalent).

I do not understand why lapply/sapply would behave any differently to calling the function on each element separately?

Upvotes: 0

Views: 30

Answers (2)

akrun
akrun

Reputation: 886938

We can just wrap with ()

(mult_six(7))
#[1] 42

The assignment to y<- is not needed. It would be

mult_six <- function(x) {
     x * 6
  }

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388797

As we know functions by default return the last line in the function, however, since a value is assigned in this function it doesn't explicitly display the result but if you use print you can see it.

print(mult_six(7))
#[1] 42

Upvotes: 1

Related Questions