[R] outputs of a function

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Thu Dec 4 15:09:06 CET 2014


This is a poor approach from a usability perspective... I suggest you create two separate functions rather than one.

However, you seem to be missing a crucial point in the use of ggplot, which also applies to lattice graphics. These functions actually don't produce output at all... they produce "grid graphics" objects that produce graphic output when printed. Interactively, this printing step is done automatically for you, but inside functions that does not happen. So, you can wrap your ggplot expression in a print function call to have your function produce the graphic output as a side effect.

print( ggplot(.....) +
......
axis.title.y = element_text(size = 8)) +
labs(title="Title") )

One of the things that is nice about grid graphics is that you can modify the object before you print it. For example, if you make a basic scatterplot function for your data, you can tack on things like labels or extra lines to aid your explanation about what is in the data just as you print it. Then you can also print it later with different notations or none at all. Having a separate graph-generating function that just returns the grid object for you to print or modify as you wish can be quite useful later.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On December 4, 2014 2:09:12 AM PST, Arnaud Michel <michel.arnaud at cirad.fr> wrote:
>Hello
>
>I have a function named FctModele13 in which
>1) I calculate a dataframe named Total and
>2) I used ggplot2.
>I have the following problem. I cannot produce simultaneously
>
>  * the graphic by ggplot2
>  * the dataframe
>
>My simplified code is the following one :
>
>
>TT <- FctModele13(ListePlusde50ans, PourcentSexeCsp, NbAn=10)
>FctModele <- function(ListePlusde50ans, PourcentSexeCsp, NbAn)
>{
># calculate Total
>.....
>.....
>Total <- data.frame(....)
>###################
># plot by ggplot
>library(ggplot2)
>ggplot(.....) +
>......
>axis.title.y = element_text(size = 8)) +
>labs(title="Title")
>
>Total
>}
>
>
>
>Any idea ?



More information about the R-help mailing list