Hello aninjaboy.
Not a silly question at all!
Objects in function calls are evaluated when you call the functions. This means that in your last example, when calling
grapher(data=mpg, xvar=displ, yvar=cyl)
R will search for objects named "displ" and "cyl" in your environement, as it has no idea that you are referring to column names of mpg.
This also means, that if these objects existed in your environment, they would be passed on to your function, causing problems there.
# ERRONEOUS CODE
displ <- mpg$displ
cyl <- mpg$cyl
grapher <- function(data, xvar, yvar){
plot(data$xvar, data$yvar)
}
grapher(data=mpg, xvar=displ, yvar=cyl)
You can see, that instead of the column names, "displ" and "cyl", the column values are passed on to the function. So in order to get your code fixed, we instead need to pass the column names in character form:
grapher_fixed <- function(data, xvar, yvar){
xvals <- data[[xvar]]
yvals <- data[[yvar]]
plot(xvals,
yvals,
xlab = xvar,
ylab = yvar)
}
grapher_fixed(data=mpg,
xvar="displ",
yvar="cyl")
I've added the "xlab" and "ylab" definitions for more useful column names.
Notice, that you extract the values of a column of name "my_column_name" by using double brackets:
data[["my_column_name"]]
Hope this helps.
Cheers!
Valentin