10

I have been trying to create functions that return a list of ggplot and am having various problems. Fundamentally however, I do not understand why this is TRUE

"data.frame" == class(c(qplot(1:10,rnorm(10)))[[1]])

when this is [TRUE,TRUE]

c('gg','ggplot') == class(qplot(1:10,rnorm(10))) 

I havent seen any questions similar to this. I see various questions that are solved by things like

lapply(someList, function(x) {
  #make ggplot, then use print(...) or whatever
  })

So I am guessing there is something about passing ggplot objects out of functions or between environments or something. Thanks for any clues about the ggplot or R that I am missing.

0

2 Answers 2

8
library(ggplot2)
p = c(qplot(1:10,rnorm(10)))
p2 = qplot(1:10,rnorm(10))

p[[1]] (same as p[['data']])) is supposed to be a dataframe. It usually holds the data for the plot.

p is a list because you used the c function.

p2 is a ggplot because that's what qplot returns.

Take a look at the attributes of each object.

attributes(p)
# $names
# [1] "data"        "layers"      "scales"      "mapping"     "theme"       "coordinates"
# [7] "facet"       "plot_env"    "labels"  

attributes(p2)
# $names
# [1] "data"        "layers"      "scales"      "mapping"     "theme"       "coordinates"
# [7] "facet"       "plot_env"    "labels"     
# 
# $class
# [1] "gg"     "ggplot"

To store many ggplot objects, use list.

ggplot.objects = list(p2,p2,p2)

The c help file shows that ggplot is not a possible output. It also states that

c is sometimes used for its side effect of removing attributes except names, for example to turn an array into a vector

If you wanted c to return ggplot objects, then you could try defining your own c.ggplot function. You'll have to read a good deal about S3 and S4 functions to understand what's going on.

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

1 Comment

Thanks @Kevin for the fast response. It isnt evident why the function c described as "..Combine.." would do that but I guess it doesnt matter since List(p2,p2) works.
4

If you have several ggplot objects in the global environment, you can make a list of them with :

ggplot_list <- Filter(function(x) is(x, "ggplot"), mget(ls()))

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.