Getting Started With R

R is both a programming language and software environment for statistical computing, which is free and open-source. To get started, you will need to install two pieces of software:

  • R, the actual programming language. – Chose your operating system, and select the most recent version. Read how to install R in Windows system from here.
  • RStudio, an excellent IDE for working with R. – Note, you must have R installed to use RStudio. RStudio is simply an interface used to interact with R. Learn how to install RStudio from here.

 

Once your R environment is ready to install a package, use the install.packages() function.

Suppose “ggplot2” is a package used for visualization. And you want to install “ggplot2” in your R environment then write install.packages(“ggplot2”).

 

#Install ggplot2 packge
install.packages("ggplot2")

Once a package is installed, it must be loaded into your current R session before being used.

 

 

#Load the ggplot2 package
library(ggplot2)

To get started, we’ll use R like a simple mathematical tool. We will show how to do basic calculation in R.

Basic Calculations:

Addition:

 

#Addition

a<-3
b<-5
c<- a+b
print(c)

Output:

##[1] 8

Subtraction:

 

a<-10
b<-5
c<- a-b
print(c)

Output:

[1] 5

Multiplication:

 

a<-10
b<-5
c<- a*b
print(c)

Output:

[1] 50

Division:

 

a<-10
b<-5
c<- a/b
print(c)

Output:

[1] 2

Exponents:

 

a<-9
b<-2
c<- a^b
d<- a^(-b)
e<- a^(1/2)
s<- sqrt(a)
print(c)
print(d)
print(e)
print(s)

Output:

> print(c)
[1] 81
> print(d)
[1] 0.01234568
> print(e)
[1] 3
> print(s)
[1] 3
>

Mathematical Constants:

 

exp(1)  #equivalent to e
pi         #equivalent to π
p=pi/3
print(p)
e=exp(1)^0
print(e)

Output:

> exp(1) #equivalent to e
[1] 2.718282
> pi #equivalent to π
[1] 3.141593
> p=pi/3
> print(p)
[1] 1.047198
> e=exp(1)^0
> print(e)
[1] 1

Logarithms:

 

log(exp(1))  #equivalent log(e)
log10(1000)   #equivalent to log10(1000)
log2(16)      #equivalent to log2(8)
log(16, base = 4)#equivalent to log4 (16)

Output:

> log(exp(1)) #equivalent log(e)
[1] 1
> log10(1000) #equivalent to log10(1000)
[1] 3
> log2(16) #equivalent to log2(8)
[1] 4
> log(16, base = 4)#equivalent to log4 (16)
[1] 2

Trigonometry:

 

s<-sin(pi / 2) #equivalent to sin(π/2)
c<- cos(0)    # equivalent to cos(0)
print(s)
print(c)

Output:

> s<-sin(pi / 2) #equivalent to sin(π/2)
> c<- cos(0) # equivalent to cos(0)
> print(s)
[1] 1
> print(c)
[1] 1

Getting Help in R:

In using R as a calculator, we have seen a number of functions: sqrt(), exp(), log() and sin(). To get documentation about a function in R, simply put a question mark in front of the function name and RStudio will display the documentation, for example:

?log
?sin
?cos

 

R Objects, Numbers, Attributes, Vectors, Coercion