Closed DominiqueMakowski closed 7 years ago
Hi, what about simple closure like the following example:
M <- cor(mtcars) # your data here
reuseMe <- function() {
corrplot(M, method = "square") # here comes your complicated corrplot setup
}
reuseMe()
...
reuseMe()
It's a good idea, unfortunately, it doesn't work in my specific case, which I'll explain a bit more.
I'd like to create a function A, within which I create the corrplot, and then store it in a list returned by the function A.
Then, I'd like to actually display the corplot bycalling the plot object from the list.
Here's what I tried:
A <- function(){
text <- "whatever else"
plot <- function() {
p <- corrplot::corrplot.mixed(r, lower="ellipse", upper="number", order = "hclust", p.mat = p, sig.level = 0.05, insig="n", tl.pos="lt")
return(p())
}
return(list(text=text, plot=plot))
}
I'd like then to be able to do this to display the plot:
output <- A()
output$plot # And, by calling this object, display the plot
However, this returns the function code 😞
function() {
p <- corrplot::corrplot.mixed(r, lower="ellipse", upper="number", order = "hclust", p.mat = p, sig.level = 0.05, insig="n", tl.pos="lt")
return(p())
}
<environment: 0x000000001b0505f0>
Do you have any advices? Thanks for your help!
no problem, functional programming is our friend:
library(corrplot)
# this function generates a list which contains a closure stored inside the "plot" element
prepareMyList <- function(r, p, text) {
plot <- function() {
# Note: variables "r" and "p" are bound from within the closure
corrplot.mixed(r, lower = "ellipse", upper = "number",
order = "hclust", p.mat = p, sig.level = 0.05,
insig = "n", tl.pos = "lt")
}
list(text = text, plot = plot, p = p) # this is returned
}
A <- prepareMyList(cor(mtcars), .01, "whatever text")
> print(A$text) # this shows the text value copied from the "text" parameter
[1] "whatever text"
> print(A$p) # this shows the variable "p" bound by the closure
[1] 0.01
A$plot() # this plots the plot bound by the closure
Your help was more than useful. Closing this 😉
For my current project, I would need to store the plot in an object (named
p
for example) and actually plot it later on in the script (using for exampleplot(p)
).However, this is not possible currently as corrplot() automatically plots the figure (and cannot be delayed) and returns a correlation matrix instead of the plotted figure.
Is there a way to modify that behaviour?
Thanks