R – Cheat Sheet

This is a cheat sheet which aims on giving all the important concepts in a very crisp manner. Just give it a read before starting a new project in R or interviewing for a Data Science or Data Analyst or Business Analyst post.
There are various advantages and disadvantages of using R over Python, but we will not dig deep into it.
This is a cheat sheet, so if you need more help, there is this awesome website www.google.com

We will start directly with Data Types which are the building blocks of a programming language.

There are 6 object types supported in R:-
1. Vectors
2. Lists
3. Matrices
4. Arrays
5. Factors
6. Data Frames

There are 6 data types of these objects:-
1. Logical – TRUE, FALSE
2. Numeric – 56.4, 45.3
3. Integer – 1,2,3,4
4. Complex – 6+2i
5. Character – “the”, “data”, “monk”
6. Raw – Any string or anything

Let’s briefly look into each Object types:-
1. Vector

If you want to create a vector with different data types then you have to use c() to define the vector

The only thing worth mentioning here is that when you use a negative index then that index will be ignored. See the example above

2. List
Vector was the simplest object in R, next in the list is a List 😛

Let’s create a list which will include a list, a vector, and a matrix. If you don’t know much about matrix, just remember it’s a 2-dimensional object which is defined as x<-matrix(c(1,2,3,4,5,6),nrow=2) to create a matrix with 2 rows.

Give names to the elements of list. See the example below

Merge two lists

Converting a list to a vector i.e. unlisting a list

Basically all you need to know about list are:-
1. How to create a list (x <- list())
2. What all can a list include? (Anything ranging from a vector to arrays, matrix, etc.)
3. Giving name to each element of the list (use the function names())
4. Accessing elements of the list (Use [])

A matrix is a 2-dimensional object, you need to specify the number of rows and columns, and dim names while declaring a matrix. Here dim names are the names given to the rows and columns 😛

x <- matrix(c(1,2,3,4,56,23),ncol=2,nrow=3,dimname=list(rownames,column names)

I think you must have got a gist of a matrix. You can definitely create two matrices and apply arithmetic operations like addition, subtraction, etc.
Matrix multiplication is also simple only, see the examples below

Accessing elements in a matrix

Arrays are able to store more than 2 dimensions in itself. Vector one dimensional, list is 2-dimensional, and now this array is more than 2 dimensional. God knows where this programming language is going 😛

Give names to columns, rows, and matrix

Leave a Reply

Your email address will not be published. Required fields are marked *