0
votes

I am in the process of writing an involved report handling large number of simulations of huge data vectors. Report output requires a number of plots generated by using ggplot2. For ease of handling, I am creating intermediate dataframe's where a column will have a ggplot object stored. I am getting the following error. Below is the sample reproducible R code

library(tidyverse)
n=100
vData=round(rnorm(n)*100, 0)
xdf=data.frame(n=n, avgVal=mean(vData), 
               vPlot=ggplot() + aes(x=vData) + geom_density(aes(y = ..count..))
    )

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class ‘c("gg", "ggplot")’ to a data.frame

## will print the plot somewhere else
print(xdf[n==100, "vPlot"])

What am I doing wrong?

1

1 Answers

3
votes

You can store the plot in a list.

library(ggplot2)

n=100
vData=round(rnorm(n)*100, 0)
xdf=data.frame(n=n, avgVal=mean(vData)) 
xdf$vPlot= list(ggplot() + aes(x=vData) + geom_density(aes(y = ..count..)))

Now you can print the plot.

print(xdf[n==100, "vPlot"])

enter image description here