Functions in R: Nested Functions Example

Hi,

In this page: https://app.dataquest.io/m/495/functions-in-r/7/nested-functions

This is what was written:

clean_data <- function(data) {
# Data cleaning code is contained in here
}

analyze_data <- function(data, analysis_parameters) {
# This function takes clean data and does analysis on it
}

create_report <- function(analyzed_data, report_parameters) {
# This function creates a nicely formatted report from the analysis
}

I was wondering if it should be this instead?

analyze_data <- function(clean_data, analysis_parameters) {
# This function takes clean data and does analysis on it
}


Thanks,
Alia

I can see that the names given for the function attributes are not ideal/confusing, but they actually don’t matter that much in a sense.

All of of these are equal:

analyze_data <- function(data, analysis_parameters) {
# This function takes clean data and does analysis on it
}

analyze_data <- function(clean_data, analysis_parameters) {
# This function takes clean data and does analysis on it
}

analyze_data <- function(some_clever_name, analysis_parameters) {
# This function takes clean data and does analysis on it
}

The reason is that names provided in the function definition live within the scope of the function, meaning that they are in general only relevant for all code, which is placed inside the function body ({}). You can think of them as a placeholder, which is replaced as soon as you are actually calling the function.

This is correct:

custom_func <- function(value) {
# Multiply a given value by 3
value <- value * 3 
return(value)
}

This not (special_value is not the same as value)

custom_func <- function(special_value) {
# Multiply a given value by 3
value <- value * 3
return(value)
}

And finally an example for several function calls

custom_func <- function(value) {
# Multiply a given value by 3
value <- value * 3 
return(value)
}

value_1<- 2
value_2 <- 4
special_value <- 100


custom_func(value_1)
# Evaluates to 6

custom_func(value_2)
# Evaluates to 12

custom_func(special_value)
# Evaluates to 300

As you can see, the name of the variable you place in the function call does not need to equal the attribute name you defined in the function itself (due to different scopes).

Best
htw