Referencial transparency is a property of most programming languages, where the name of the variables does not affect the outcome.
Let's start with a simple example:
add1 <- function(variable) {
return(variable + 1)
}
add1(1)
#> [1] 2
x <- 1
add1(x)
#> [1] 2
y <- 1
add1(y)
#> [1] 2
add1(variable = y)
#> [1] 2
The name of the variable does not affect the outcome, name it x
, y
, or whatever you like. This happens in most programming languages.
However, in R we can find out the name of the variable, and behave like trolls:
add1 <- function(variable) {
original_varname <- as.character(substitute(variable))
if (original_varname == "z") {
return(variable + 200) # TROLOLOLOLO
}
return(variable + 1)
}
x <- 1
add1(x)
#> [1] 2
y <- 1
add1(y)
#> [1] 2
z <- 1
add1(z)
#> [1] 201
hundreds <- c(100, 200, 300)
thousands <- c(1000, 2000, 3000)
data.frame(hundreds, thousands)
#> hundreds thousands
#> 1 100 1000
#> 2 200 2000
#> 3 300 3000
Look at those convenient column names! 😃
Or in plots:
hundreds <- c(100, 200, 300)
thousands <- c(1000, 2000, 3000)
plot(hundreds, thousands)
Look at those axes labels!
Referencial transparency is very convenient for interactive programming and coding, but it can become a nightmare when programming, so use it sparingly!
Created on 2022-02-17 by the reprex package (v2.0.1)