The R syntax

Start by showing an example of a script

Example of a simple R script

Commenting

Use # signs to comment. Comment liberally in your R scripts. Anything to the right of a # is ignored by R.

Assignment operator

<- is the assignment operator. Assigns values on the right to objects on the left, it is like an arrow that points from the value to the object. Mostly similar to = but not always. Learn to use <- as it is good programming practice. Using = in place of <- can lead to issues down the line.

In RStudio, typing Alt + - (push Alt, the key next to your space bar at the same time as the - key) will write <- in a single keystroke.

= should only be used to specify the values of arguments in functions for instance read.csv(file="data/some_data.csv").

Allowable object names

Objects can be given any name such as x, current_temperature, or subject_id. You want your object names to be explicit and not too long. They cannot start with a number (2x is not valid but x2 is). R is case sensitive (e.g., weight_kg is different from Weight_kg). There are some names that cannot be used because they represent the names of fundamental functions in R (e.g., if, else, for, see here for a complete list). In general, even if it’s allowed, it’s best to not use other function names (e.g., c, T, mean, data, df, weights). In doubt check the help to see if the name is already in use. It’s also best to avoid dots (.) within a variable name as in my.dataset. It is also recommended to use nouns for variable names, and verbs for function names.

Functions and their arguments

Let’s look at a simple function call:

surveys <- read.csv(file="data/surveys.csv")

The file= part inside the parentheses is called an argument, and most functions use arguments. Arguments modify the behavior of the function. Typically, they take some input (e.g., some data, an object) and other options to change what the function will return, or how to treat the data provided.

Most functions can take several arguments, but most are specified by default so you don’t have to enter them. To see these default values, you can either type args(read.csv) or look at the help for this function (e.g., ?read.csv).

args(read.csv)
## function (file, header = TRUE, sep = ",", quote = "\"", dec = ".", 
##     fill = TRUE, comment.char = "", ...) 
## NULL

If you provide the arguments in the exact same order as they are defined you don’t have to name them:

read.csv(file="data/surveys.csv", header=TRUE) # is identical to:
read.csv("data/surveys.csv", TRUE)

However, it’s usually not recommended practice because it’s a lot of remembering to do, and if you share your code with others that includes less known functions it makes your code difficult to read. (It’s however OK to not include the names of the arguments for basic functions like mean, min, etc…)

Another advantage of naming arguments, is that the order doesn’t matter:

read.csv(file="data/surveys.csv", header=TRUE) # is identical to:
read.csv(header=TRUE, file="data/surveys.csv")

Good practices

There are two main ways of interacting with R: using the console or by using script files (plain text files that contain your code).

The recommended approach when working on a data analysis project is dubbed “the source code is real”. The objects you are creating should be seen as disposable as they are the direct realization of your code. Every object in your analysis can be recreated from your code, and all steps are documented. Therefore, it is best to enter as little commands as possible in the R console. Instead, all code should be written in script files, and evaluated from there. That is where RStudio is really useful as it makes the passing of code between your script and the R console easy. The R console should be used to inspect objects, test a function or get help. You should periodically clear your environment and re-create it from the code in your script to make sure that the objects you are working can be reproduced if you sent the script to someone else. For that reason, when R asks you to save your Workpace image (.Rdata) don’t save it.

Similarly, you should separate the original data (raw data) from intermediate datasets that you may create for the need of a particular analysis. For instance, you may want to create a data/ directory within your working directory that stores the raw data, and have a data_output/ directory for intermediate datasets and a figure_output/ directory for the plots you will generate.

Seeking help

I know the name of the function I want to use, but I’m not sure how to use it

If you need help with a specific function, let’s say barplot(), you can type:

?barplot

If you just need to remind yourself of the names of the arguments, you can use:

args(lm)

If the function is part of a package that is installed on your computer but don’t remember which one, you can type:

??geom_point

I want to use a function that does X, there must be a function or it but I don’t know which one…

If you are looking for a function to do a particular task, you can use help.search() (but only looks through the installed packages):

help.search("kruskal")

If you can’t find what you are looking for, you can use the rdocumention.org website that search through the help files across all packages available.

I want to know what kinds of packages are available and what analyses are appropriate for data particular to my field

R task views are reviews of R packages conducted by domain experts. They provide a summary of different package that can do what functions related to specific sub-areas of many fields.

I found a package that I want to use, but I feel I need a tutorial for it.

Head to the CRAN page for it. Look under the downloads section.

All packages will have a Reference Manual. This is a pdf of all the functions in that package with all of the documentation for each function (the same as if you had typed ?functionName in the console).

Sometimes listed after the Reference Manual is a “Vignette.” If there is, you’re in luck! This is a tutorial that the package author has written.

Sometimes there are also web pages associated with packages. Those are also good places to look for help.

I am stuck… I get an error message that I don’t understand

Start by googling the error message. However, this doesn’t always work very well because often, package developers rely on the error catching provided by R. You end up with general error messages that might not be very helpful to diagnose a problem (e.g. “subscript out of bounds”).

However, you should check stackoverflow. Search using the [r] tag. Most questions have already been answered, but the challenge is to use the right words in the search to find the answers: http://stackoverflow.com/questions/tagged/r

The Introduction to R can also be dense for people with little programming experience but it is a good place to understand the underpinnings of the R language.

The R FAQ is dense and technical but it is full of useful information.

Asking for help

The key to get help from someone is for them to grasp your problem rapidly. You should make it as easy as possible to pinpoint where the issue might be.

Try to use the correct words to describe your problem. For instance, a package is not the same thing as a library. Most people will understand what you meant, but others have really strong feelings about the difference in meaning. The key point is that it can make things confusing for people trying to help you. Be as precise as possible when describing your problem

If possible, try to reduce what doesn’t work to a simple reproducible example. If you can reproduce the problem using a very small data.frame instead of your 50,000 rows and 10,000 columns one, provide the small one with the description of your problem. When appropriate, try to generalize what you are doing so even people who are not in your field can understand the question.

To share an object with someone else, if it’s relatively small, you can use the function dput(), it will output R code that can be used to recreate the exact same object as the one in memory:

dput(head(iris)) # iris is an example data.frame that comes with R
## structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
##     Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
##     1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
##     0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 
##     1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length", 
## "Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 
## 6L), class = "data.frame")

If the object is larger, provide either the raw file (i.e., your CSV file) with your script up to the point of the error (and after removing everything that is not relevant to your issue). Alternatively, in particular if your questions is not related to a data.frame, you can save any R object to a file:

saveRDS(iris, file="/tmp/iris.rds")

The content of this file is however not human readable and cannot be posted directly on stackoverflow. It can how be sent to someone by email who can read it with this command:

some_data <- readRDS(file="~/Downloads/iris.rds")

Last, but certainly not least, always include the output of sessionInfo() as it provides critical information about your platform, the versions of R and the packages that you are using, and other information that can be very helpful to understand your problem.

sessionInfo()
## R version 3.1.2 (2014-10-31)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## 
## locale:
## [1] LC_COLLATE=English_United States.1252 
## [2] LC_CTYPE=English_United States.1252   
## [3] LC_MONETARY=English_United States.1252
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
## [1] digest_0.6.4     evaluate_0.5.5   formatR_1.0      htmltools_0.2.6 
## [5] knitr_1.7        rmarkdown_0.3.11 stringr_0.6.2    tools_3.1.2     
## [9] yaml_2.1.13

Where to ask for help?

  • Your friendly colleagues: if you know someone with more experience than you, they might be able and willing to help you.
  • Stackoverflow: ) if your question hasn’t been answered before and is well crafted, chances are you will get an answer in less than 5 min. They also incentivize posting and answering with reputation points.
  • The R-help: it is read by a lot of people (including most of the R core team), a lot of people post to it, but the tone can be pretty dry, and it is not always very welcoming to new users. If your question is valid, you are likely to get an answer very fast but don’t expect that it will come with smiley faces. Also, here more than everywhere else, be sure to use correct vocabulary (otherwise you might get an answer pointing to the misuse of your words rather than answering your question). You will also have more success if your question is about a base function rather than a specific package.
  • If your question is about a specific package, see if there is a mailing list for it. Usually it’s included in the DESCRIPTION file of the package that can be accessed using packageDescription("name-of-package"). You may also want to try to email the author of the package directly.
  • There are also some topic-specific mailing lists (GIS, phylogenetics, etc…), the complete list is here.

More resources