Getting started with R

R is a widely used language for statistical computation, analysis and graphics. It is a freely available software and constantly upgraded and updated by the academic and industry users across the world. Due to its wide adaptation, help on R is easily available to its users, through various online forums.

To be able to work with R, you need to first complete the following steps in the sequence mentioned.

  1. Download and install on your computer, the latest version of R from the CRAN website https://cran.r-project.org/

  2. Download and install the user interface R-Studio https://www.rstudio.com/products/RStudio/#Desktop

The first steps after you have installed R-studio

This document provides an introduction to basic numeric operations in R. This is a good first step to start learning and getting familiar with R.

Let us start with basic operations by typing the below expressions in the command prompt in the R-studio Console (Console is one of the windows that appears when you launch Rstudio and contains a “>” prompt within the window). In what is shown below, the portion that appears in the shaded box is the command you should type in the command prompt (then hit enter) and what follows in the unshaded box right after it is the output you should see.

Arithmetic operations

# Addition
2 + 3
## [1] 5
# Subtraction
2 - 3
## [1] -1
# Multiplication
2 * 3
## [1] 6
# Division
2/3
## [1] 0.6666667
#exponent or to-the-power
2^3
## [1] 8
#computing to the power of e, where e is mathematical constant approximately 2.718
exp(1)
## [1] 2.718282
exp(5)
## [1] 148.4132
#natural logarithm to the base e
log(5)
## [1] 1.609438

Logical operations

# logical operations: checking less than , great than , equal to
(2<3)
## [1] TRUE
(3<2)
## [1] FALSE
(2==2)
## [1] TRUE
(2 != 2)
## [1] FALSE
(2<=3)
## [1] TRUE
# To get a numeric answer for a logical operation
(2<3)*1
## [1] 1
# One can also add and subtract logical outcomes
(2<3) + (3<2) -(2==2)
## [1] 0

Creating numeric variables

Often we will want to store a numerical outcome in a variable. So, we would assign a value such as 2 to a variable with a particular name such as x. The assignment operator to use is ‘\(<-\)’ (i.e. less than sign followed without spaces by dash or hiphen). We put x on the left hand side of the assignment operator and the value to be assigned on the right hand side of the assignment operator.

x<-2
print(x)
## [1] 2
y<- 2+3-5 + (9>7)*1
print(y)
## [1] 1
# We can then perform operations on the variables and then store it in a third variable
z<- x+y + x^y

Note that R stores treates variables as a vectors and in this case it understands from the right hand side that the vector is of length 1.

length(z)
## [1] 1
print(z)
## [1] 5

length(z) is returning the length of the vector which is 1. The [1] in the output is indicating that the first element of vector z is 5, i.e. z[1] is 5.