This lesson will try to get you familiarized with R by teaching a few simple lessons and commands.
R is a console that you can use as a giant calculator. For example, results in 4.
2+3
## [1] 5
That would be silly of course, but in a pinch, there’s always R!
R comes pre-loaded with functions that you can call up by writing them in a script. We will explore some of these functions shortly. For now, it is important to note that whenever you need help with a function you call up the help file by writing ‘?’ in front of it.
The key to understanding R is that it an object-based environment. This means that you navigate R by assigning values to objects and then performing operations on these objects. For example, we can perform the same addition from before by assigning the values 2 and 3 to R objects as below. To assign a value we use “<-”.
a<-2 # a gets 2
b<-3 # b gets 3
# And so when we call
a #the console returns 2
## [1] 2
b #the console returns 3
## [1] 3
a + b #returns the operation 2+3 which is equal to 5
## [1] 5
#the order in which you place the operations matters so that a-b and b-a is not the same
a-b
## [1] -1
b-a
## [1] 1
Objects can take almost any value. For example, objects can store results, and they can also store other objects. Be careful though, cause objects will not auto-update when you change any objects they contain, and they will be easily be renamed.
z <- a+b #z gets the addition of a + b
a <-9 # I've now changed the value of a, but z does not know this so
z # returns 5 instead of 12, until I rerun the object z
## [1] 5
z <- a+b
z # now 12
## [1] 12
In statistis, matrix algebra is fundamental. R easily deals with vectors and matrices. Below, we first create a vector, perform some mathematical operations on them, and then do the same with matrices.
a<-c(1,2,3,4,5,6) #the entires are separated by commas.
2*a # will multiply 2 times each entry in the vector
## [1] 2 4 6 8 10 12
a+2
## [1] 3 4 5 6 7 8
A<-matrix(data=c(1,2,3,4,5,6), nrow=3, ncol=2,byrow = FALSE) #the entires are separated by commas, I specify the number of rows and columns, and the order by which is fills in the data.
A
## [,1] [,2]
## [1,] 1 4
## [2,] 2 5
## [3,] 3 6
A*2 # will multiply 2 times each entry in the matrix
## [,1] [,2]
## [1,] 2 8
## [2,] 4 10
## [3,] 6 12
A+2
## [,1] [,2]
## [1,] 3 6
## [2,] 4 7
## [3,] 5 8