samedi 27 janvier 2018

R function using ifelse to plot returns data and plot

Reproducable example

require(ggplot2)

A <- data.frame(x = 1:5, y = 1:5)
B <- data.frame(x = 1:5, y = (1:5)^2)

plotA <- ggplot(data = A, aes(x = x, y = y)) + geom_line()
plotB <- ggplot(data = B, aes(x = x, y = y)) + geom_line()

myfn <- function(){print(plotA)}
myfn()

myfn2 <- function(printA = TRUE){ifelse(printA, print(plotA), print(plotB))}
myfn2(TRUE)

myfn() returns exactly what I would expect, specifically plotA. myfn2(TRUE) on the otherhand does return plotA, but it also returns the data behind the plot. How do I just return the plot? (With more complicated plots the amount of data returned can be significant)

Aucun commentaire:

Enregistrer un commentaire