-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvectors.qmd
653 lines (447 loc) · 11.2 KB
/
vectors.qmd
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# Vectors {#sec-vectors}
## Questions
- What are vectors, and why are they essential in R?
- What are the different types of vectors and their key characteristics?
- How does one create a vector?
- What operations can be performed on a vector?
- How do I create and access different elements within a vector?
- Can I combine and manipulate vectors to achieve specific tasks?
- What are some common functions for working with vectors?
## Learning Objectives
- Define and create vectors in R.
- Understand how to perform basic operations on vectors.
- Understand the concept of vectors as fundamental data structures in R.
- Master the creation and manipulation of vectors using various techniques.
- Identify and differentiate between different types of vectors based on their elements.
- Utilize functions and operators to combine, subset, and transform vectors with ease.
- Apply your understanding of vectors to enhance your R coding and data analysis efficiency.
## Lesson Content
### Introduction
A vector is a collection of elements of the same data type, and they are a basic data structure in R programming.
Vectors cannot be of mixed data type. The most common way to create a vector is with `c()`, where “c” stands for combine. In R, vectors do not have dimensions; therefore, they cannot be defined by columns or rows. Vectors can be divided into atomic vectors and lists (discussed in the "Data Structures" {@sec-data-structure-1} section). The atomic vectors include logical, character, and numeric (integer or double).
Additionally, R is a vectorized language because mathematical operations are applied to each element of the vector without the need to loop through the vector.
Examples of vectors made up of different data types are shown below:
- Numbers
```{r}
c(2, 10, 16, -5)
```
- Characters
```{r}
c("R", "RStudio", "Shiny", "Quarto")
```
- Logicals
```{r}
c("TRUE", "FALSE", "TRUE")
```
### Sequence Generation
To generate a vector with a sequence of consecutive numbers, we can use: `sequence()`, or `seq()`.
Generate a sequence using `:`
```{r}
a <- 9:18
a
```
```{r}
a_rev <- 18:9
a_rev
```
```{r}
a_rev_minus <- 5:-3
a_rev_minus
```
Generate a sequence using `sequence()`
```{r}
b <- sequence(7)
b
```
```{r}
c <- sequence(c(5,9))
c
```
Generate a sequence using `seq()`
The `seq()` function has four main arguments: `seq(from, to, by, length.out)`, where "from" and "to" are the starting and ending elements of the sequence. Additionally, "by" is the difference between the elements, and "length.out" is the maximum length of the vector.
```{r}
d <- seq(2,20,by=2)
d
```
```{r}
f <- seq(2,20, length.out=5)
f
```
```{r}
h <- seq(20,2,by=-2)
h
```
```{r}
j <- seq(20, 2, length.out=3)
j
```
The `seq()` function can also be used with the arguments first, by, and length.
`seq(first, by = ___, length = ____)`
Example
```{r}
seq(3, by = 4, length = 30)
```
Repeating vectors
To create a repeating vector, we can use `rep()`.
`rep(number, times)`
```{r}
k <- rep(c(0,3,6), times = 3)
k
```
`rep(range, times)`
```{r}
l <- rep(2:6, each = 3)
l
```
`rep(number or range, length.out)`
```{r}
m <- rep(7, length.out = 20)
m
n <- rep(7:10, length.out = 20)
n
```
Random number generation
The `runif()` function can be used to generate a specific number of random numbers between a minimum and maximum value.
`runif(n, min = 0, max = 1)`
```{r}
runif(5, min = 3, max = 100)
```
**NOTE**: If you run the previous code block multiple times you will get different answers. Use `set.seed()` to get a similar sequence every time you run the calculation.
```{r}
set.seed(12345)
runif(5, min = 3, max = 100)
```
### More functions to manipulate vectors
Generate a random vector with 50 elements
```{r}
set.seed(54321)
sam <- runif(50, min = 3, max = 100)
sam
```
Sample
```{r}
sample(sam, size = 15)
```
To get the same sample repeatedly
```{r}
set.seed(1234)
sample(sam, size = 15)
```
```{r}
sort(sam)
```
```{r}
rev(sort(sam))
```
```{r}
quantile(sam)
```
Create two vectors and look at the similarities/differences between the two
```{r}
set.seed(2468)
vec_top_1 <- seq(2, by = 6, length = 100)
vec_top_2 <- seq(4, by = 4, length = 100)
```
```{r}
vec_top_1
```
```{r}
vec_top_2
```
```{r}
union(vec_top_1, vec_top_2)
```
```{r}
intersect(vec_top_1, vec_top_2)
```
```{r}
setdiff(vec_top_1, vec_top_2)
```
### Vector Operations
Vectors of equal length can be operated on together. If one vector is shorter, it will get recycled, as its elements are repeated until it matches the elements of the longer vector. When using vectors of unequal lengths, it would be ideal if the longer vector is a multiple of the shorter vector.
1. Basic Vector Operations
```{r}
vec_1 <- 1:10
```
```{r}
vec_1 * 12 # multiplication
```
```{r}
vec_1 + 12 # addition
```
```{r}
vec_1 - 12 # subtraction
```
```{r}
vec_1 / 3 # division
```
```{r}
vec_1^4 # power
```
```{r}
sqrt(vec_1) # square root
```
2. Operations on vectors
Operations on vectors of equal length Additionally, we can perform operations on two vectors of equal length.
a. Create two vectors
```{r}
vec_3 <- 5:14
vec_3
```
```{r}
vec_4 <- 12:3
vec_4
```
b. Perform various arithmetic operations
```{r}
vec_3 + vec_4
```
```{r}
vec_3 - vec_4
```
```{r}
vec_3 / vec_4
```
```{r}
vec_3 * vec_4
```
```{r}
vec_3 ^ vec_4
```
3. Functions that can be applied to vectors
The functions listed below can be applied to vectors:
a. `any()`
b. `all()`
c. `nchar()`
d. `length()`
e. `typeof()`
Examples
```{r}
any(vec_3 > vec_4)
```
```{r}
any(vec_3 < vec_4)
```
```{r}
all(vec_3 > vec_4)
```
```{r}
all(vec_3 < vec_4)
```
```{r}
length(vec_3)
```
```{r}
length(vec_4)
```
```{r}
typeof(vec_3)
```
```{r}
typeof(vec_4)
```
Determine the number of letters in a character
```{r}
vec_5 <- c("R", "RStudio", "Shiny", "Quarto")
```
```{r}
nchar(vec_5)
```
3. Vectors and mathmatical/statistical operations
A variety of mathematical operations can be performed on vectors. These operations together with examples are listed below.
a. Create a new vector
```{r}
stat_math_vec_1 <- seq(2, by = 6, length = 120)
stat_math_vec_1
```
b. Perform mathematical operations on the vector
- Length
```{r}
length(stat_math_vec_1)
```
- Sum
```{r}
sum(stat_math_vec_1)
```
- Minimum
```{r}
min(stat_math_vec_1)
```
- Maximum
```{r}
max(stat_math_vec_1)
```
- Mean
```{r}
mean(stat_math_vec_1)
```
- Median
```{r}
median(stat_math_vec_1)
```
- Quantile
```{r}
quantile(stat_math_vec_1)
```
- Standard Deviation
```{r}
sd(stat_math_vec_1)
```
- Inter-Quartile Range (IQR)
```{r}
IQR(stat_math_vec_1)
```
- Cumulative Sum
```{r}
cumsum(stat_math_vec_1)
```
- Range
```{r}
range(stat_math_vec_1)
```
- Cut This function cuts a range of values into bins and specifies labels for each bin.
The argument "breaks" can be the number of bins, or it can be specific break points.
```{r}
cut(stat_math_vec_1, breaks = 6)
cut(stat_math_vec_1, breaks = c(0, 120, 240, 360, 480, 600, 720))
```
- Pretty
This function creates a sequence of equally spaced values that are rounded to the closest integer.The argument "n" lists the number of intervals.
```{r}
pretty(stat_math_vec_1)
pretty(stat_math_vec_1, n = 20)
```
- Trigonometric functions
```{r}
sin(stat_math_vec_1)
```
```{r}
cos(stat_math_vec_1)
```
```{r}
tan(stat_math_vec_1)
```
- Logarithmic functions
```{r}
log(stat_math_vec_1)
```
```{r}
log2(stat_math_vec_1)
```
```{r}
log10(stat_math_vec_1)
```
4. Miscellaneous functions
<!-- -->
a. Changing the case of a character vector
```{r}
char_vec <- c("a", "b", "c", "d")
```
```{r}
char_vec_upper <- toupper(char_vec)
char_vec_upper
```
```{r}
char_vec_lower <- tolower(char_vec_upper)
char_vec_lower
```
4. Recycling of vectors
```{r}
vec_3 + c(10, 20)
```
```{r}
vec_3 + c(10, 20, 30)
# Will result in a warning as the longer vector is not a multiple of the shorter one
```
D) Accessing elements of a vector and subsetting
To access the elements of a vector, we can use numeric-, character-, or logical-based indexing.
Examples
1. Name the columns of a vector with names().
<!-- -->
a) Create the vector.
```{r}
vec_name <- 1:5
vec_name
```
b) Name the individual elements.
```{r}
names(vec_name) <- c("a", "c", "e", "g", "i")
vec_name
```
2. Use the vector index to filter
```{r}
vec_index <- 1:5
vec_index
```
a) Logical vector as an index
```{r}
vec_index[c(TRUE, FALSE, TRUE, FALSE, TRUE)]
```
b) Filter vector based on an index
```{r}
vec_index[1:3]
```
c) Access a vector using its position
```{r}
vec_index[4]
```
With negative indexing, every element except the one specified is returned.
```{r}
vec_index[-2]
```
```{r}
vec_index[c(2,4)]
```
d) Modify a vector using indexing
```{r}
vec_index
```
```{r}
vec_index[5] <- 1000
```
```{r}
vec_index
```
E) Create matrices by combining vectors by row and column
<!-- -->
1. Create four new vectors
```{r}
vec_mat_df_1 <- seq(2,20, length.out=10)
vec_mat_df_2 <- rep(2:6, each = 2)
vec_mat_df_3 <- runif(10, min = 3, max = 100)
vec_mat_df_4 <- sequence(10)
vec_mat_df_1
vec_mat_df_2
vec_mat_df_3
vec_mat_df_4
```
2. Create a new matrix by combining each vector as a column, `cbind()`.
```{r}
new_matrix <- cbind(vec_mat_df_1, vec_mat_df_2, vec_mat_df_3, vec_mat_df_4)
new_matrix
str(new_matrix)
class(new_matrix)
```
3. Create a new matrix by combining each vector as a row, `rbind()`.
```{r}
new_matrix <- rbind(vec_mat_df_1, vec_mat_df_2, vec_mat_df_3, vec_mat_df_4)
new_matrix
str(new_matrix)
class(new_matrix)
```
## Exercises
i. Create a numeric vector with values 1 through 5 using `c()` and extract the middle element from the vector using the described subsetting methods.
ii. Generate a sequence of even numbers from 2 to 10 using the `seq()` function, and calculate the total sum and average of this new vector.
iii. Create a vector of student ages (between 16 and 20, n = 10), calculate their average and standard deviation, and identify students younger than 18.
iv. Use logical indexing to subset elements from a vector based on a condition.
v. Perform element-wise addition and multiplication on two newly created numeric vectors of the same length.
vi. Concatenate two newly created character vectors to create a longer vector.
vii. Create a named vector with elements representing days of the week.
viii. Use vector functions to find the length, sum, and mean of a numeric vector.
ix. Use the functions `sort()` or `rev()` to arrange elements in ascending, descending, or reversed order.
x. Use functions like `which()` or `match()` to locate elements based on conditions or matching values.
xi. How can you append elements to an existing vector?
xii. When binding vectors together, what is the difference between `cbind()` and `rbind()`?
xiii. Explore other vector capabilities like recycling, naming elements, and using vector lengths in your R code.
## Summary
Vectors are an essential data structure for data analysis purposes. In this chapter, I have demonstrated the different types of vectors, how to generate vectors, and the various types of vector operations that can be performed. Now that we have a deeper understanding of vectors, it is time to explore other data structures (that are useful for data analysis) in the subsequent chapters.