Returning Plots and Strings from R Functions with ggplot2

To return both the plot and the string “Helo stackoverflow” from your function, you can modify it as follows:

plotGG <- function (gdf){
  x11()
  ggplot (spectrumTable, aes (massIon, intensityIon)) +
    geom_segment(aes(xend = massIon, colour = assigned), yend = 0) +
    facet_wrap( ~ source, scales = "free_y")
  
  list(plot = plot(ggplot(gdf, aes(massIon, intensityIon)) + 
                  geom_segment(aes(xend = massIon, colour = assigned), yend = 0) +
                     facet_wrap( ~ source, scales = "free_y")), message = "Helo stackoverflow")
}

print(plotGG(gdf))

This code will return a list containing the plot and the string “Helo stackoverflow”. The list() function is used to create a list in R, where you can store different types of values. In this case, we’re using it to hold both the plot (which is returned by plot()) and the message (“Helo stackoverflow”).


Last modified on 2024-09-11