7.1 Looking behind the curtain

A good way to start learning to program in R is to see what others have done. We can start by briefly peeking behind the curtain. In Chapter 5 we made use of the theme_classic() function when customising our ggplot figures. With many functions in R, if you want to have a quick glance at the machinery behind the scenes, we can simply write the function name but without the (). This is the same trick we used in Chapter 5 to alter the theme_classic() style of ggplot2 to make theme_rbook().

Note that to view the source code of base R packages (those that come with R) requires some additional steps which we won’t cover here (see this link if you’re interested), but for most other packages that you install yourself, generally entering the function name without () will show the source code of the function.

## function (base_size = 11, base_family = "", base_line_size = base_size/22, 
##     base_rect_size = base_size/22) 
## {
##     theme_bw(base_size = base_size, base_family = base_family, 
##         base_line_size = base_line_size, base_rect_size = base_rect_size) %+replace% 
##         theme(panel.border = element_blank(), panel.grid.major = element_blank(), 
##             panel.grid.minor = element_blank(), axis.line = element_line(colour = "black", 
##                 linewidth = rel(1)), strip.background = element_rect(fill = "white", 
##                 colour = "black", linewidth = rel(2)), complete = TRUE)
## }
## <bytecode: 0x7fe770557e80>
## <environment: namespace:ggplot2>

What we see above is the underlying code for this particular function. As we did in Chapter 5, we could copy and paste this into our own script and make any changes we deemed necessary. This approach isn’t limited to ggplot2 functions and can be used for other functions as well, although tread carefully and test the changes you’ve made.

Don’t worry overly if most of the code contained in functions doesn’t make sense immediately. This will be especially true if you are new to R, in which case it seems incredibly intimidating. To help with that, we’ll begin by making our own functions in R in the next section.