Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Exercise – commands in blue, comments in green, outputs in black

Let’s create a small vector and perform a few basic functions:


> i <- c(2,4,6,8) # this small vector is called i

> i # allows you to view your vectors contents


[1] 2 4 6 8

> i+1 # add 1 to each of the numbers


[1] 3 5 7 9

> i+5 # add 5 to each of the numbers


[1] 7 9 11 13

> i*2 # multiply each number by 2


[1] 4 8 12 16

> i/2 # divide each number by 2


[1] 1 2 3 4

> j <- i-1 # create a new vector j


>j
[1] 1 3 5 7

> i+j # add vector i to vector j


[1] 3 7 11 15

> mean(i) # calculates the mean


[1] 5

> sd(i) # calculates the standard deviation


[1] 2.581989

Depending on the format of certain data sets, when calculating standard deviation, mean
etc. you may need to call a specific row:

>x=somedataset[,1] #rename your data here and select just the first column
[row, column]
>sd(x)

> sqrt(i) # square root


[1] 1.414214 2.000000 2.449490 2.828427

> max(i) # outputs the max of the specified vector


[1] 8
> min(i) # outputs the minimum of the specified vector
[1] 2

RStudio has a lot of preloaded datasets, to browse the library use the following:

> data() # a list will prepopulate and you will be able to scroll through, if you hover on a certain
dataset, a description will appear.
>data(“AirPassengers”)

>View(AirPassengers) # to open the dataset and manually scroll through and view its contents –
data set will appear at the top left of RStudio

> mean(AirPassengers)
[1] 280.2986

> median(AirPassengers)
[1] 265.5

> min(AirPassengers)
[1] 104

> max(AirPassengers)
[1] 622

> sd(AirPassengers)
[1] 119.9663

> quantile(AirPassengers)
0% 25% 50% 75% 100%
104.0 180.0 265.5 360.5 622.0

> summary(AirPassengers)
Min. 1st Qu. Median Mean 3rd Qu. Max.
104.0 180.0 265.5 280.3 360.5 622.0

> hist(AirPassengers)
> boxplot(AirPassengers)

> plot(AirPassengers)
References:

Black, K. (2015). R Tutorial. Retrieved from:


http://www.cyclismo.org/tutorial/R/index.html

Quick, J. (2009). Summary Statistics Analysis Example. Retrieved from:


https://www.r-bloggers.com/wp-content/uploads/2009/11/sumStatsAnalysisExample1.txt

Spector, P. (2015). Introduction to R. Retrieved from:


https://www.stat.berkeley.edu/~spector/Rcourse.pdf

You might also like