I want to write a function that returns both a dataframe and a ggplot. Simply printing the ggplot in the function is not enough, as it will need to be used later in ggarrange()
. I need to store both the ggplot and the dataframe in variables to be used later in a pipeline.
For example, if I want to return a box plot and the top 20% highest-distance cars:
library('ggplot2')
plotCars <- function(d){
dm <- suppressMessages(melt(d))
p <- ggplot(dm, aes(x=variable, y=value, fill=variable)) +
geom_boxplot(width=0.2)
q <- quantile(d$dist, prob=c(0.8))
dq <- d[d$dist > q[1],]
return(c(list(p), dq))
}
obj <- plotCars(cars)
Calling obj[[1]]
prints the plot as expected.
But the dataframe gets stored as invidual columns in the output object. E.g. obj[2]
gives the $speed
column, and obj[3]
gives the $dist
column.
This ruins the structure of the dataframe and undermines the next steps of the pipeline that use it. How do I fix this?