Reputation: 711
Hi I have a function called basic_plot(), which will generate a plot if the variable plot_function = TRUE else it return a NULL. it is as follows
plot_function = TRUE;
basic_plot = function() {
if(plot_function) {
par(mfrow = c(1,3))
plot(1:10,1:10,type = "o")
plot(10:1,1:10,type = "o")
plot(1:10,rep(5,10),type = "o")
} else {
NULL;
}
}
basic_plot();
should generate a plot with tree panels populated with some lines. This function along with the variable it depends on is embedded with in some other code. What I would like to know is how I can tell an if() statement if the plot has been drawn? for example
if(is.null(basic_plot())) {
print("I haven't drawn the plot yet")
} else {
print("I have drawn the plot and want to do more stuff.")
}
The problem with the above is if a function plots a graph it is considered a null. so this will never know when I draw the plot e.g
plot_function = TRUE;
is.null(basic_plot())
[1] TRUE
plot_function = FALSE;
is.null(basic_plot())
[1] TRUE
The true application for this is with in a shiny app but actually thought this could be a generic R query. I cannot return anything other than generate the plot in the basic_plot() function (avoiding the obvious return something after the plot is drawn). I am hoping for an alternative function to is.null() such as has this function does something or not?
Cheers, C
Upvotes: 0
Views: 394
Reputation: 2060
In your function basic_plot
the plot(1:10,rep(5,10),type = "o")
command does not assign anything to the function, so it is still NULL
For example below will assign TRUE
to your function.
plot_function = TRUE;
basic_plot = function() {
if(plot_function) {
par(mfrow = c(1,3))
plot(1:10,1:10,type = "o")
plot(10:1,1:10,type = "o")
plot(1:10,rep(5,10),type = "o")
TRUE
} else {
NULL;
}
}
basic_plot();
For storing plots as an object, recordPlot()
is used:
myplot<-recordPlot()
Upvotes: 1
Reputation: 10543
Simple answer: return either TRUE or FALSE in your function:
basic_plot = function() {
if(plot_function) {
par(mfrow = c(1,3))
plot(1:10,1:10,type = "o")
plot(10:1,1:10,type = "o")
plot(1:10,rep(5,10),type = "o")
return(TRUE) # Now the function will plot, then return TRUE
} else {
return(FALSE) # Now the function will return FALSE instead of NULL
}
}
# We can make this a function too
check_plot <- function() {
if(basic_plot()) {
print("I have drawn the plot and want to do more stuff.")
} else {
print("I haven't drawn the plot yet")
}
}
# Now we can simply check:
plot_function <- TRUE
check_plot()
plot_function <- FALSE
check_plot()
# Note: it is generally bad practice to use global variables like this!
Upvotes: 1