R Programming Practice Weeks 1-3

Umair Durrani

Data Types

Introduction to Data Types in R

Vector

# Create an empty vector
my.vector <- vector(mode='numeric', length=20)
my.vector
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Attributes

  • Attributes of a dataframe
df <- data.frame(names = c("Robert", "Jonah", "Umair"), age = c(15, 25, 26))
attributes(df)
$names
[1] "names" "age"  

$row.names
[1] 1 2 3

$class
[1] "data.frame"

Coercion

  • Coercing a numeric vector to a character vector
my.vector
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
class(my.vector)
[1] "numeric"
my.vector <- as.character(my.vector)
class(my.vector)
[1] "character"

Matrix

  • Attributes of a matrix
my.matrix <- matrix(10:17,nrow=2, ncol=4)
my.matrix
     [,1] [,2] [,3] [,4]
[1,]   10   12   14   16
[2,]   11   13   15   17
attributes(my.matrix)
$dim
[1] 2 4

Matrix from a Vector

dim(my.vector) <- c(4, 5)
my.vector
     [,1] [,2] [,3] [,4] [,5]
[1,] "0"  "0"  "0"  "0"  "0" 
[2,] "0"  "0"  "0"  "0"  "0" 
[3,] "0"  "0"  "0"  "0"  "0" 
[4,] "0"  "0"  "0"  "0"  "0" 
  • my.vector is no longer a vector

Binding Vectors to create matrix

p <- 5:8
q <- 6:10
rbind(p,q)
  [,1] [,2] [,3] [,4] [,5]
p    5    6    7    8    5
q    6    7    8    9   10
cbind(p,q)
     p  q
[1,] 5  6
[2,] 6  7
[3,] 7  8
[4,] 8  9
[5,] 5 10

List of different data types and lists

my.list <- list("umair.durrani", TRUE, 56, list(1:6), 0 + (0+3i))
str(my.list)
List of 5
 $ : chr "umair.durrani"
 $ : logi TRUE
 $ : num 56
 $ :List of 1
  ..$ : int [1:6] 1 2 3 4 5 6
 $ : cplx 0+3i

What my.list looks like

[[1]]
[1] "umair.durrani"

[[2]]
[1] TRUE

[[3]]
[1] 56

[[4]]
[[4]][[1]]
[1] 1 2 3 4 5 6


[[5]]
[1] 0+3i

Vector for Categorical Data = Factor

my.factor <- factor(c("male", "female", "male", "male", "female", "female", 
    "female"), levels = c("female", "male"))
my.factor
[1] male   female male   male   female female female
Levels: female male