forked from rdpeng/rprogdatascience
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvectorized.Rmd
85 lines (61 loc) · 1.63 KB
/
vectorized.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
# Vectorized Operations
[Watch a video of this chapter](https://youtu.be/YH3qtw7mTyA)
```{r,echo=FALSE}
knitr::opts_chunk$set(comment = NA, prompt = TRUE, collapse = TRUE)
```
Many operations in R are _vectorized_, meaning that operations occur
in parallel in certain R objects. This allows you to write code that
is efficient, concise, and easier to read than in non-vectorized
languages.
The simplest example is when adding two vectors together.
```{r}
x <- 1:4
y <- 6:9
z <- x + y
z
```
Natural, right? Without vectorization, you'd have to do something like
```{r,prompt=FALSE}
z <- numeric(length(x))
for(i in seq_along(x)) {
z[i] <- x[i] + y[i]
}
z
```
If you had to do that every time you wanted to add two vectors, your
hands would get very tired from all the typing.
Another operation you can do in a vectorized manner is logical
comparisons. So suppose you wanted to know which elements of a vector
were greater than 2. You could do he following.
```{r}
x
x > 2
```
Here are other vectorized logical operations.
```{r}
x >= 2
x < 3
y == 8
```
Notice that these logical operations return a logical vector of `TRUE`
and `FALSE`.
Of course, subtraction, multiplication and division are also vectorized.
```{r}
x - y
x * y
x / y
```
## Vectorized Matrix Operations
Matrix operations are also vectorized, making for nicly compact
notation. This way, we can do element-by-element operations on
matrices without having to loop over every element.
```{r}
x <- matrix(1:4, 2, 2)
y <- matrix(rep(10, 4), 2, 2)
## element-wise multiplication
x * y
## element-wise division
x / y
## true matrix multiplication
x %*% y
```