3.3 Structuring your code
3.3.1 User-defined functions
One of the best ways to improve your reach as a data scientist is to write functions. Functions allow you to automate common tasks in a more powerful and general way than copy-and-pasting.
— (Grolemund and Wickham 2018)
# An example of user-defined function named myFunction
function(num) {
myFunction <- num * 3
num <- }
In R, the return value of a function is always the very last expression that is evaluated. Because the chars variable is the last expression that is evaluated in this function, that becomes the return value of the function.
Note that there is a return() function that can be used to return an explicity value from a function, but it is rarely used in R (we will discuss it a bit later in this chapter).
Finally, in the above function, the user must specify the value of the argument num. If it is not specified by the user, R will throw an error.
3.3.2 Projects, files and working directories
Exercise: take 5 minutes to configure the look and feel of RStudio e.g., rearrange the panes or use a dark theme. Choose the Preferences menu option and then explore the different Options (General, Code, …).
3.3.3 Using R note books and rmarkdown
A problem with writing lots of small individual R scripts is it can be hard to make sense of what they are all about, even if we insert a few comments. For this reason RStudio offers a very powerful alternative in the form of RMarkdown. We will be using RMarkdown as our primary way of writing and sharing R code for this module and strongly recommend it for all data analysis.
RMarkdown is a specialised form of markdown which is a text-based simple markup language (cf hypertext markup language or html). There are three significant factors:
1. the formatting markup is simple and human readable
2. code of many programming languages including R can be embedded
3. it can be rendered into many formats including html and pdf
filename.Rmd
for Rmarkdown
The differences between R notebooks and R markdown https://stackoverflow.com/questions/43820483/difference-between-r-markdown-and-r-notebook
To give an idea of the power and flexibiity of markdown, this book is entirely written using a variant of RMarkdown called Bookdown and the {bookdown} package within RStudio.
References
Grolemund, Garrett, and Hadley Wickham. 2018. “R for Data Science.”