Understanding scoping of nested functions

I'm attempting to refactor a script by splitting it into multiple functions, having a main function and "help functions". Here I stumbled upon a problem which can be reduced to the following example:

g <- function(a,b){       # help function
    a^2 + b^2 - c

f <- function(a,b,c,d){   # main function

The problem here is, that f cannot be computed because g does not know what c is, but why is that the case?

I've read here that if R doesn't know a variable/argument in a function, it searches for that missing variable/argument in the outer function/environment.

Why does g still not know the value c which gets declared by f?

Read more here: https://stackoverflow.com/questions/68473954/understanding-scoping-of-nested-functions

Content Attribution

This content was originally published by Maryam at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: