R Cheat sheet

Guilherme Kunigami edited this page Jun 13, 2017 · 12 revisions

Comments

The # character starts a comment for the current line

Blocks of code

R has the concept of blocks of code delimited by curly braces: {}. One important observation is that it returns the result of the last expression. Example:

> c <- {
  a = 3 + 7;
  b = a + 1;
}
> c
[1] 11

Functions

Functions are defined anonymously and can be assigned to. R returns the last statement (the return keyword is optional).

> f <- function (x) {
x + 1;
}
> f(1)
[1] 2

Functions in R can take default values and named arguments. For example:

> f <- function (a, b=2) {
a + b;
}
> f(3)
[1] 5
> f(b=3, a=3)
[1] 6

Modules

Require module (e.g. dplyr):

require(dplyr)

Reading from file

outcomeTable <- read.csv(
  '/absolute/path/filename.csv',
  colClasses = "character"
)

Data frames

Simply put, data Frames are to matrices what lists are to vectors. They usually represent tables, where each column from the table may have different types. We can construct a data frame from a set of vectors. They have to have the same number of elements, but if not, R applies the repetition principle:

> x <- data.frame(c(1, 2, 3, 4), c(1, 2), 1);
> x
  c.1..2..3..4. c.1..2. X3
1             1       1  3
2             2       2  3
3             3       1  3
4             4       2  3

Selecting columns

dataframe[c('col_name_a', 'col_name_b')]

Exploring a data frame

  • head(frame) - Print first rows
  • str(frame) - Print states

Packages

  • Install: install.packages('fortunes')
  • Import: library(fortunes)

dplyr

Dplyr is a great way to manipulate datasets, especially for those familiar with SQL.

FAQ

  • List built-in datasets: data(). They can be referred by their names. e.g. airquality
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.