Hello,
I am running into issues while using arguments
in R function calls. The code below shows a minimum working example
to give an idea of the problem that I am facing. Would it be possible for anyone to have a
look and tell me why it is the case that the arguments are working as intended
in the first case and not in the last case?
[ This is a silly question and I do apologize in advance.
I guess that having extensively worked in Stata I am thinking about
the way local Stata macros work as I am writing the code below and that is what
is causing the error.]
# MWE
# ====================
library(ggplot2)
data(mpg)
# When I define the function this way :
grapher <- function(data, xvar, yvar){
attach(data)
plot(xvar, yvar)
hist(xvar)
hist(yvar)
detach(data)
}
grapher(mpg, displ, cyl) # the code works
# Explicitly specifying the vectors using $ notation works as well :
grapher2 <- function(xvar, yvar){
plot(xvar, yvar)
}
grapher2(mpg$displ, mpg$cyl)
# Why does this piece of code fail?
grapher <- function(data, xvar, yvar){
plot(data$xvar, data$yvar)
}
grapher(data=mpg, xvar=displ, yvar=cyl)
Many thanks for your assistance.