Home > Back-end >  Print multiple plot functions from same parent function
Print multiple plot functions from same parent function

Time:11-05

I would like to use a parent function that creates two additional plot functions, and when I call the parent function, I would like both plots to be returned. Ideally, I would like the plots to be returned as two separate objects instead of using something like par() to combine the two plots into a single image.

The code below only returns the second of the two plots.

test_fx <- function() {
  
  # Define the first plot
  plot1_fx <- function() {
    plot(x=c(1,2,3),y=c(3,4,5), type='l')
    abline(v=1.5, col="red", lwd=5)
  }
  
  # Define the second plot
  plot2_fx <- function() {
    plot(x=c(1,2,3),y=c(5,4,3), type='l')
    abline(v=2.5, col="blue", lwd=5)
  }

  # Return the plots
  plot1_fx()
  plot2_fx()

}


# Call the main function
test_fx()

CodePudding user response:

If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

If you use an explicitly define return(), you can only return one thing. multi-argument returns are not permitted. If you want to return two things, you need to put them inside of something else, like a list:

test_fx <- function() {
  
  # Define the first plot
  plot1_fx <- function() {
    plot(x=c(1,2,3),y=c(3,4,5), type='l')
    abline(v=1.5, col="red", lwd=5)
  }
  
  # Define the second plot
  plot2_fx <- function() {
    plot(x=c(1,2,3),y=c(5,4,3), type='l')
    abline(v=2.5, col="blue", lwd=5)
  }
  
  return(invisible(list(plot1_fx(), plot2_fx())))
  
}
test_fx()

I added an extra invisible call to suppress printing the list.

CodePudding user response:

Base function plot does not return a useful value, it returns NULL. To return both plots, have the function (test_fx) return functions. test_fx is a functions factory. Its return value is a named list of functions.
Then, you can assign the return value to a list and call the member functions when needed.

Note: After posting my answer I read M.Viking's and it makes sense to return the function's list invisibly. Credits for noticing it go to @M.Viking.

test_fx <- function() {
  plots_list <- list(
    # Define the first plot
    plot1_fx = function() {
      plot(x=c(1,2,3),y=c(3,4,5), type='l')
      abline(v=1.5, col="red", lwd=5)
    },
    
    # Define the second plot
    plot2_fx = function() {
      plot(x=c(1,2,3),y=c(5,4,3), type='l')
      abline(v=2.5, col="blue", lwd=5)
    }
  )
  # Return the plots
  invisible(plots_list)
}

# Call the main function
p <- test_fx()
p$plot1_fx()

p$plot2_fx()

Created on 2022-11-04 with reprex v2.0.2

  • Related