-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lecture 2 Objects.Rmd
115 lines (89 loc) · 2.09 KB
/
Lecture 2 Objects.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
---
title: 'Lecture 2: Objects'
author: "David McAllister"
date: "Monday 31st October, 2016"
output:
ioslides_presentation: default
---
## Objective of session
* Describe the different types of R objects
* Describe how R coerces different types of atomic vectors
## Much of the following is taken from
Advanced R by Hadley Wickham
http://adv-r.had.co.nz/
## Types of data object
| | Homogeneous | Heterogeneous |
|----|---------------|---------------|
| 1d | Atomic vector | List |
| 2d | Matrix | Data frame |
| nd | Array | |
## Atomic vectors
* Logical, integer, double (numeric) and character
* Logical > integer > double > character
* Must be the same type
* created with c() for combine
## Quiz
What will you get if you do the following ...
```{r, eval=FALSE}
c(1L, 6L, 10L)
c(1.1, 2.1, 4.5)
c(1, 2, 4.1, "missing")
c(TRUE, FALSE, 1)
```
When try to combine different types changes vector type
**runs down the hill**
## Lists versus vectors
``` {r}
object1 <- c (1, 2, 3)
object2 <- c ("a", "b", "c", "d", "e")
c(object1, object2)
list1 <- list (object1, object2)
str (list1)
```
## Lists are recursive
``` {r}
list2 <- list (list1, list1)
str(list2)
list3 <- c (list1, list1)
str(list3)
```
## Matrices
2d extension of vectors
```{r}
mymatrix <- matrix (1:25, nrow = 5)
print (mymatrix)
dim (mymatrix)
```
## Data frames
* Type of list
+ Allows multiple types; eg character, double, logical
+ Has dimensions
```{r}
head (iris)
dim(iris)
```
## Create data frame
```{r}
mydata <- data.frame (people = c("Sarah", "Nynke", "Colin", "Stephanie"),
gender = c(0,0,1,0),
stringsAsFactors = FALSE)
mydata
str( as.list (mydata))
```
## Names
```{r}
# Vectors can have names
c(one = 1, two = 2)
# Matrices have colnames and rownames
matrix (1:4, nrow = 2, dimnames = list(c("one", "two"), c("A", "B")))
# Dataframes have names
names(iris)
```
## Same function, different action
```{r, echo = -3}
a_vector <- rep(1:5, 2)
a_matrix <- matrix (a_vector, nrow = 5)
par(mfcol = c(1,2))
plot(a_vector)
plot(a_matrix)
```