Cyrillm_44
Cyrillm_44

Reputation: 711

in R Return a logical if my function plots a graph

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

Answers (2)

Erdem Akkas
Erdem Akkas

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

Scott Ritchie
Scott Ritchie

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

Related Questions