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!