Why can you pass an "undefined variable" to a function?

Advertisements

originally asked here

ggplot(data = bechdel, aes(x = domgross_2013)) +
  geom_histogram(bins = 10, color="purple", fill="white") +
  labs(title = "Domestic Growth of Movies", x = " Domestic Growth")

How come we are able to pass the column we would like to map to the x value (domgross_2013)? It seems to be passed like a variable rather then a string.

This is different from this post because in order to reach that post you must know that on standard evaluation exists and is the cause of allowing you to pass an "undefined variable". I didn’t know that this evaluation existed, and the explanation within that post is for people who have a much large R foreknowledge as well as understanding of what the "undefined variable" is

>Solution :

For the second question, the reason you can pass x like a variable rather than a string is due to non-standard evaluation. Effectively, the function arguments are captured rather than being immediately evaluated, and then evaluated within the scope that they exist. For example, with the quote() function, we can capture the input as-is, rather than looking for the value inside var. Then, we can evaluate it inside another environment like the mtcars data frame.

var <- quote(mpg)
> var
mpg

eval(var, mtcars)
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4

We can make a similar use of NSE within functions:

f <- function(x) {
  input <- substitute(x)
  print(input)
  eval(input, mtcars)
}

Here, we capture whatever was passed to the argument, and then execute it in the scope of the mtcars data frame.

f(cyl)
cyl
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

You can read more about this at the above link and here.

Leave a ReplyCancel reply