Reputation: 3
I will try to run the ggplot_build inside a function and it returns the error: Error in eval(expr, envir, enclos) : object 'myData' not found Here is the code:
# Summarise number of movie ratings by year of movie
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
nums <- tapply(df$length, df$year, length)
data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)), number=as.vector(nums))
}))
p <- ggplot(mry, aes(x=year, y=number, group=rating))
p + geom_line()
function_mm <- function(myData){
for(j in 1:2){
p1 <- ggplot(myData, aes(x=myData[,2], y=myData[,3])) + geom_line()
g1 <- ggplot_gtable(ggplot_build(p1))
}
return(p1)
}
Q1 <- function_mm(mry)
The code is running correctly when it is outside a function:
for(j in 1:2){
p1 <- ggplot(myData, aes(x=myData[,2], y=myData[,3])) + geom_line()
g1 <- ggplot_gtable(ggplot_build(p1))
}
Thanks in advance!
Upvotes: 0
Views: 578
Reputation: 132969
You made the classic mistake of using aes
(with its non-standard evaluation) when you should use aes_string
:
function_mm <- function(myData){
for(j in 1:2){
xy <- names(myData)[c(2, 3)]
p1 <- ggplot(myData, aes_string(x=xy[1], y=xy[2])) + geom_line()
g1 <- ggplot_gtable(ggplot_build(p1))
}
return(p1)
}
Q1 <- function_mm(mry)
#works
Upvotes: 3