I am getting strange behaviour when putting plots inside functions (using ggplot with R from 'R Studio' 0.99.484).
I don't understand why locally scoped variables cannot be used to generate the plot. Perhaps you can enlighten me, and tell me of the right way to do it.
Here is a small code snippet reproducing my troubles:
# This works:
x1 <- seq(0,90,10)
ggplot() + geom_line(aes(x=x1,y=x1))
# This yields error below:
f1 <- function() {
x2 <- seq(0,90,10)
ret <- ggplot() + geom_line(aes(x=x2,y=x2))
return(ret)
}
f1()
Error in eval(expr, envir, enclos) : object 'x2' not found
# This fixes the error: but why myX needs to be global?
f1 <- function() {
myX <<- seq(0,90,10)
ret <- ggplot() + geom_line(aes(x=myX,y=myX))
return(ret)
}
f1()
# This yields error below:
f2 <- function(d) {
ret <- ggplot() + geom_line(aes(x=d,y=d))
return(ret)
}
f2(x1)
Error in eval(expr, envir, enclos) : object 'd' not found
# This fixes the error making all global: is this the right way to do it?
f2 <- function(d) {
myX <<- d
ret <- ggplot() + geom_line(aes(x=myX,y=myX))
return(ret)
}
f2(x1)