[SOLVED] Explaining a Function inside a Function in R

Issue

I got confused when I stumbled upon this code as you don’t need to give "y" a value to operate, how does it get its value?

f <- function(x) {
    g <- function(y) {
            y + z
    }
    z <- 4
    x + g(x)}

because if I add ran this code

z <- 10
f(3)

it will give the result (10), where the second function got its "y" value?

Solution

When you call function g() inside f(), you passed "y" value by using g(x). Whatever value you assigned to x will be assigned to y inside function g().
So the result is x+g(x)=x+x+z=3+3+4=10

Answered By – Bufei

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *