Show Menu
Cheatography

R - Beginner Syntax Cheat Sheet (DRAFT) by

A summary of all the R programming language syntax I have learned so far. Still learning; I'll be back now and then

This is a draft cheat sheet. It is a work in progress and is not finished yet.

General variable assignment

Assignment statem­ents:
var_name = new_value
OR
var_name <- new_value
Variables names: The variable name must start with a letter and can contain numbers and letters as well as the special characters underscore and period.
Note: Contrary to other languages R does not have a command for declaring a variable, but instead a variable is created once a value is assigned to it.

Arithmetic operators

+
Addition - adds together two values.
-
Subtra­­ction - subtracts one value from another.
*
Multip­­li­c­ation - multiplies two values together.
/
Division - divides one value from the other.
** OR ^
Expone­ntial - to the power of the next value
Arithmetic operators: Used to perform common mathem­­atical operat­­ions.
Preced­­ence: Precedence and associ­­at­ivity are as normal as in maths.

Access variables of a dataframe

Calling individual variables from a dataframe:
datafr­ame­$va­r_name
 

Some misc commands

cat()
Prints all of its comma separated arguments (conca­ten­ating them).
read.csv()
Reads a csv file (in the same location)
head()
To get a broad overview of the variables that are contained in the dataframe as well as the different variable levels (first 6 rows(?))
summary()
Gives the summary statistics of a variable - min, 1st quartile, median, mean, 3rd quartile, maximum
as.fac­tor()
Convert to catego­rical variable
barplot()
Creates a barplot for the given table
table()
[TBC]
Internal help option: Writing ? in front of the command opens R docume­ntation of the command.

Vector creation and assignment

Creating a list of numbers manually:
vector­_name <- c(no1, no2, no3, etc.)


Creating a list of numbers in a sequence:
vector­_name <- seq(start, stop, step)
(starts from start and ends at exactly stop at increments of step)
Vector: A vector is a 1D set of the same type of object. Most often, a vector will simply be a sequence of numbers.
Note: Similarly to variables, a vector is created once a value is assigned to it.
 

Comments

Single line comments:
# Comment1

code # Comment2
Comments: Comments are ignored by the computer, they exist simply to make the code easier for people to unders­­tand.

Indexing vectors

Getting 1 index:
vec_na­me[­ind­ex_no]


Getting multiple index in a row:
vec_na­me[­sta­rt_­ind­ex:­end­_index]
Note: The indexing is 1-based so it starts at 1 instead of 0 like most other progra­mming languages do.

Basic math functions

log(x)
Natural log of x
exp(x)
Expone­ntial of x
max(x)
Largest element in the set x
min(x)
Smallest element in the set x
sum(x)
Sum all values in x
mean(x)
Mean of x
median(x)
Median of x
round(x,n)
Round x to n decimal places
length(x)
Number of values in x