Vector


To create a vector

v1 = c(1,2,3)
v2 <- c(4,5,6)

Get vector’s length

length(v1)
## [1] 3

Check whether all or any is true

v3 = c(F,T,T)
all(v3)
## [1] FALSE
any(v3)
## [1] TRUE

Integer slicing

v1[1:2]
## [1] 1 2

Boolean slicing

v4 = c(NA,1,2)
v1[is.na(v4)]
## [1] 1

Name a vector

v5 = c(fifth=1,2,3,4,5)
v5
## fifth                         
##     1     2     3     4     5

Factors

Convert a vector to factor

fv = c(1,2,2,3,1,2,3,3,1,2,3,3,1)
f1 = factor(fv)
f1
##  [1] 1 2 2 3 1 2 3 3 1 2 3 3 1
## Levels: 1 2 3
f2 = factor(fv,labels=c("I","II","III"))
f2
##  [1] I   II  II  III I   II  III III I   II  III III I  
## Levels: I II III

Rename the level of a factor

levels(f2) = c('S','M','L')
f2
##  [1] S M M L S M L L S M L L S
## Levels: S M L

Matrix


To create a Matrix using numbers

m1 = matrix(1:20, nrow = 4, ncol=5)
m1
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    5    9   13   17
## [2,]    2    6   10   14   18
## [3,]    3    7   11   15   19
## [4,]    4    8   12   16   20

To create a Matrix using vextors

m2 = cbind(v1,v2)
m2
##      v1 v2
## [1,]  1  4
## [2,]  2  5
## [3,]  3  6

Matrix multiplication

m2 %*% t(m2)
##      [,1] [,2] [,3]
## [1,]   17   22   27
## [2,]   22   29   36
## [3,]   27   36   45

List


To create a list holding vectors

l1 <- list(first=c(1,2,3),second=c(2,3,4))
l1
## $first
## [1] 1 2 3
## 
## $second
## [1] 2 3 4

To create an empty list

l2 = vector(mode='list', length=3)
l2
## [[1]]
## NULL
## 
## [[2]]
## NULL
## 
## [[3]]
## NULL

List slicing

l1$first[1]
## [1] 1
l1[2]
## $second
## [1] 2 3 4
l1[[2]]
## [1] 2 3 4

Append a list

l3 = list(first=1, second=2)
l3[[3]]=3

l3
## $first
## [1] 1
## 
## $second
## [1] 2
## 
## [[3]]
## [1] 3

Get/Set names of a list

names(l3)[3] = 'third'

l3
## $first
## [1] 1
## 
## $second
## [1] 2
## 
## $third
## [1] 3

DataFrames


To create a dataframe using vectors

d1 = data.frame(col1 = v1, col2=v2, col3=c(7,8,9))
d1
##   col1 col2 col3
## 1    1    4    7
## 2    2    5    8
## 3    3    6    9

Shape of a dataframe

dim(d1)
## [1] 3 3
nrow(d1)
## [1] 3
ncol(d1)
## [1] 3

DataFrame matrix subsetting

d1[1,]
##   col1 col2 col3
## 1    1    4    7
d1[,2]
## [1] 4 5 6
d1[1,2]
## [1] 4

DataFrame list subsetting

d1$col1
## [1] 1 2 3
d1[[2]]
## [1] 4 5 6

Append a datafrmam

cbind(d1, data.frame(col4=c(10,11,12)))
##   col1 col2 col3 col4
## 1    1    4    7   10
## 2    2    5    8   11
## 3    3    6    9   12
# Give same column names
rbind(d1, data.frame(col1=0,col2=0,col3=0))
##   col1 col2 col3
## 1    1    4    7
## 2    2    5    8
## 3    3    6    9
## 4    0    0    0

Tibbles

Tibbles are data frames, but they tweak some older behaviours to make life a little easier.