0

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.