This repository has been archived by the owner on Aug 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basics.Rmd
1057 lines (836 loc) · 29.6 KB
/
basics.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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Simple Beginnings {#basics}
```{r setup, include=FALSE}
source("etc/common.R")
```
We begin by introducing the basic elements of R.
You will use these less often than you might expect,
but they are the building blocks for the higher-level tools introduced in Chapter \@ref(tidyverse),
and offer the comfort of familiarity.
Where we feel comparisons would aid understanding,
we provide short examples in Python.
## Learning Objectives
- Name and describe R's atomic data types and create objects of those types.
- Explain what 'scalar' values actually are in R.
- Identify correct and incorrect variable names in R.
- Create vectors in R and index them to select single values, ranges of values, and selected values.
- Explain the difference between `NA` and `NULL` and correctly use tests for each.
- Explain the difference between a list and a vector.
- Explain the difference between indexing with `[` and with `[[`.
- Use `[` and `[[` correctly to extract elements and sub-structures from data structures in R.
- Create a named list in R.
- Access elements by name using both `[` and `$` notation.
- Correctly identify cases in which back-quoting is necessary when accessing elements via `$`.
- Create and index matrices in R.
- Create `for` loops and `if`/`else` statements in R.
- Explain why vectors cannot be used directly in conditional expressions and correctly use `all` and `any` to combine their values.
- Define functions taking a fixed number of named arguments and/or a variable number of arguments.
- Explain what vectorization is and create vectorized equivalents of unnested loops containing simple conditional tests.
## How do I say hello?
We begin with a traditional greeting.
In Python, we write:
```{python python-hello}
print("Hello, world!")
```
We can run the equivalent R in the RStudio Console (Figure \@ref(fig:console)):
```{r r-hello}
print("Hello, world!")
```
```{r console, echo=FALSE, fig.cap="RStudio Console"}
knitr::include_graphics("figures/basics/console.png")
```
Python prints what we asked for,
but what does the `[1]` in R's output signify?
Is it perhaps something akin to a line number?
Let's take a closer look by evaluating a couple of expressions without calling `print`:
```{r r-quotes}
'This is in single quotes.'
"This is in double quotes."
```
`[1]` doesn't appear to be a line number;
let's ignore it for now and do a little more exploring.
> Note that R uses double quotes to display strings even when we give it a single-quoted string
> (which is no worse than Python using single quotes when we've given it doubles).
## How do I add numbers?
In Python,
we add numbers using `+`.
```{python python-addition}
print(1 + 2 + 3)
```
We can check the type of the result using `type`,
which tells us that the result `6` is an integer:
```{python python-type}
print(type(6))
```
What does R do?
```{r r-addition}
1 + 2 + 3
```
```{r r-typeof}
typeof(6)
```
R's type inspection function is called `typeof` rather than `type`,
and it returns the type's name as a string.
That's all fine,
but it seems odd for integer addition to produce a double-precision floating-point result.
Let's try an experiment:
```{r typeof-6}
typeof(6)
```
Ah: by default,
R represents numbers as floating-point values,
even if they look like integers when written.
We can force a literal value to be an integer by appending an upper-case `L`
(which stands for "long integer"):
```{r typeof-6-int}
typeof(6L)
```
Arithmetic on integers does produce integers:
```{r integer-addition}
typeof(1L + 2L + 3L)
```
and if we want to convert a floating-point number to an integer we can do so:
```{r convert-to-integer}
typeof(as.integer(6))
```
But wait:
what is that dot in `as.integer`'s name?
Is there an object called `as` with a [method](glossary.html#method) called `integer`?
The answer is "no":
`.` is (usually) just another character in R;
like the underscore `_`,
it is used to make names more readable.
## How do I store many numbers together?
The Elder Gods do not bother to learn most of our names
because there are so many of us and we are so ephemeral.
Similarly, we only give a handful of values in our programs their own names;
we lump the rest together into lists, matrices, and more esoteric structure
so that we too can create, manipulate, and dispose of multitudes with a single imperious command.
The most common such structure in Python is the list.
We create lists using square brackets
and assign a list to a variable using `=`.
If the variable does not exist, it is created:
```{python python-list}
primes = [3, 5, 7, 11]
print(primes)
```
Since assignment is a [statement](glossary.html#statement)
rather than an [expression](glossary.html#expression),
it has no result,
so Python does not display anything when this command is run.
The equivalent operation in R uses a function called `c`,
which stands for "column" and which creates a [vector](glossary.html#vector):
```{r r-vector}
primes <- c(3, 5, 7, 11)
primes
```
Assignment is done using a left-pointing arrow `<-`
(though other forms exist, which we will discuss later).
As in Python,
assignment is a statement rather than an expression,
so we enter the name of the newly-created variable to get R to display its value.
Now that we can create vectors in R,
we can explain the errant `[1]` in our previous examples.
To start,
let's have a look at the lengths of various things in Python:
```{python py-len-list}
print(primes, len(primes))
```
```{python py-len-int, error=TRUE}
print(len(4))
```
Fair enough:
the length of a list is the number of elements it contains,
and since a [scalar](glossary.html#scalar) like the integer 4 doesn't contain elements,
it has no length.
What of R's vectors?
```{r r-len-vec}
length(primes)
```
Good—and numbers?
```{r r-len-int}
length(4)
```
That's surprising.
Let's have a closer look:
```{r r-typeof-vec}
typeof(primes)
```
That's also unexpected:
the type of the vector is the type of the elements it contains.
This all becomes clear once we realize that *there are no scalars in R*.
`4` is not a single lonely integer,
but rather a vector of length one containing the value 4.
When we display its value,
the `[1]` that R prints is the index of its first value.
We can prove this by creating and displaying a longer vector:
```{r long-vec}
c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
```
In order to help us find our way in our data,
R automatically breaks long lines
and displays the starting index of each line.
These indices also show us that R counts from 1 as humans do,
rather than from zero.
(There are a great many myths about why programming languages do the latter.
[The truth is stranger than any fiction could be.][hoye-zero])
## How do I index a vector?
Python's rules for indexing are simple once you understand them
(a statement which is also true of quantum mechanics and necromancy).
To avoid confusing indices with values,
let's create a list of color names and index that:
```{python py-index-0}
colors = ["eburnean", "glaucous", "wenge"]
print(colors[0])
```
```{python py-index-top}
print(colors[2])
```
```{python py-index-error, error=TRUE}
colors[3]
```
```{python py-index-negative}
print(colors[-1])
```
Indexing the equivalent vector in R with the indices 1 to 3 produces unsurprising results:
```{r r-index-first}
colors <- c("eburnean", "glaucous", "wenge")
colors[1]
```
```{r r-index-last}
colors[3]
```
What happens if we go off the end?
```{r r-index-out-of-range}
colors[4]
```
R handles gaps in data using the special value [`NA`](glossary.html#NA) (short for "not available"),
and returns this value when we ask for a nonexistent element of a vector.
But it does more than this—much more.
In Python,
a negative index counts backward from the end of a list.
In R,
we use a negative index to indicate a value that we don't want:
```{r r-index-negative}
colors[-1]
```
But wait.
If every value in R is a vector,
then when we use 1 or -1 as an index,
we're actually using a vector to index another one.
What happens if the index itself contains more than one value?
```{r r-index-vec-error, error=TRUE}
colors[1, 2]
```
That didn't work because R interprets `[i, j]` as being row and column indices,
and our vector has only one dimension.
What if we create a vector with `c(...)` and use that as a subscript?
```{r r-index-with-vec}
colors[c(3, 1, 2)]
```
That works, and allows us to repeat elements:
```{r r-index-vec-repeat}
colors[c(1, 1, 1)]
```
Note that this is [pull indexing](glossary.html#pull-indexing),
i.e.,
the value at location *i* in the index vector specifies which element of the source vector
is being pulled into that location in the result vector (Figure \@ref(fig:pull-indexing)).
```{r pull-indexing, echo=FALSE, fig.cap="Pull Indexing"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/basics/pull-indexing.pdf")
} else {
knitr::include_graphics("figures/basics/pull-indexing.svg")
}
```
We can also select out several elements:
```{r r-index-negative-multiple}
colors[c(-1, -2)]
```
But we cannot simultaneously select elements in (with positive indices) and out (with negative ones):
```{r r-mixed-indexing, error=TRUE}
colors[c(1, -1)]
```
That error message is suggestive:
what happens if we use 0 as an index?
```{r r-index-zero}
colors[0]
```
In order to understand this rather cryptic response,
we can try calling the function `character` ourselves
with a positive argument:
```{r r-create-char-vec}
character(3)
```
Ah:
`character(N)` constructs a vector of empty strings of the specified length.
The expression `character(0)` presumably therefore means
"an [empty vector](glossary.html#empty-vector) of type character".
From this,
we conclude that the index 0 doesn't correspond to any elements,
so R gives us back something of the right type but with no content.
As a check,
let's try indexing with 0 and 1 together:
```{r r-zero-ignored}
colors[c(0, 1)]
```
So when 0 is mixed with either positive or negative indices, it is ignored,
which will undoubtedly lead to some puzzling bugs.
What if in-bounds and out-of-bounds indices are mixed?
```{r r-in-and-out}
colors[c(1, 10)]
```
That is consistent with the behavior of single indices.
## How do I create new vectors from old?
Modern Python encourages programmers to use [list comprehensions](glossary.html#list-comprehension)
instead of loops,
i.e.,
to write:
```{python py-list-comp}
original = [3, 5, 7, 9]
doubled = [2 * x for x in original]
print(doubled)
```
instead of:
```{python py-list-loop}
doubled = []
for x in original:
doubled.append(2 * x)
print(doubled)
```
If `original` is a NumPy array, we can shorten this to `2 * original`.
R provides this capability in the language itself:
```{r r-vec-comp}
original <- c(3, 5, 7, 9)
doubled <- 2 * original
doubled
```
Modern R strongly encourages us to [vectorize](glossary.html#vectorize) computations in this way,
i.e.,
to do operations on whole vectors at once rather than looping over their contents.
To aid this,
all arithmetic operations work element by element on vectors:
```{r vector-ops}
tens <- c(10, 20, 30)
hundreds <- c(100, 200, 300)
tens + hundreds / (tens * hundreds)
```
If two vectors of unequal length are used together,
the elements of the shorter are [recycled](glossary.html#recycle).
This behaves sensibly if one of the vectors is a scalar—it is just re-used as many times as necessary:
```{r scalar-vector}
hundreds + 5
```
If both vectors have several elements,
the shorter is repeated as often as necessary.
This works,
but is so likely to lead to hard-to-find bugs that R produces a warning message:
```{r vec-length-mismatch}
thousands <- c(1000, 2000)
hundreds + thousands
```
R also provides vectorized alternatives to `if`-`else` statements.
If we use a vector containing the logical (or Boolean) values `TRUE` and `FALSE` as an index,
it selects elements corresponding to `TRUE` values:
```{r vector-conditional}
colors # as a reminder
colors[c(TRUE, FALSE, TRUE)]
```
This is called [logical indexing](glossary.html#logical-indexing),
though to the best of my knowledge illogical indexing is not provided as an alternative.
The function `ifelse` uses this to do what its name suggests:
select a value from one vector if a condition is `TRUE`,
and a corresponding value from another vector if the condition is `FALSE`:
```{r ifelse-func}
before_letter_m <- colors < "m"
before_letter_m # to show the index
ifelse(before_letter_m, colors, c("comes", "after", "m"))
```
All three vectors are of the same length,
and the first (the condition) is usually constructed using the values of one or both of the other vectors:
```{r ifelse-example}
ifelse(colors < "m", colors, toupper(colors))
```
```{r ifelse-fig, echo=FALSE, fig.cap="Vector Conditionals"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/basics/if-else.pdf")
} else {
knitr::include_graphics("figures/basics/if-else.svg")
}
```
## How else does R represent the absence of data?
The special value `NA` means "there's supposed to be a value here but we don't know what it is."
A different value, [`NULL`](glossary.html#null), represents the absence of a vector.
It is not the same as a vector of zero length,
though testing that statement produces a rather odd result:
```{r null-comparison}
NULL == integer(0)
```
The safe way to test if something is `NULL` is to use the function `is.null`:
```{r is-null}
is.null(NULL)
```
Circling back,
the safe way to test whether a value is `NA` is *not* to use direct comparison:
```{r na-comparison}
threshold <- 1.75
threshold == NA
```
The result is `NA` because if we don't know what the value is,
we can't know if it's equal to `threshold` or not.
Instead,
we should always use the function `is.na`:
```{r is-na}
is.na(threshold)
is.na(NA)
```
## How can I store a mix of different types of objects?
One of the things that newcomers to R often trip over is the various ways in which structures can be indexed.
All of the following are legal:
```{r subscript-examples, eval=FALSE}
thing[i]
thing[i, j]
thing[[i]]
thing[[i, j]]
thing$name
thing$"name"
```
but they can behave differently depending on what kind of thing `thing` is.
To explain, we must first take a look at lists.
A [list](glossary.html#list) in R is a vector that can contain values of many different types.
(The technical term for this is [heterogeneous](glossary.html#heterogeneous),
in contrast with a [homogeneous](glossary.html#homogeneous) data structure
that can only contain one type of value.)
We'll use this list in our examples:
```{r list-of-things}
thing <- list("first", c(2, 20, 200), 3.3)
thing
```
The output tells us that the first element of `thing` is a vector of one element,
that the second is a vector of three elements,
and the third is again a vector of one element;
the major indices are shown in `[[…]]`,
while the indices of the contained elements are shown in `[…]`.
(Again,
remember that `"first"` and 3.3 are actually vectors of length 1.)
> In keeping with R's conventions,
> we will henceforth use `[[` and `[` to refer to the two kinds of indexing
> rather than `[[…]]` and `[…]`.
## What is the difference between `[` and `[[`?
The output above strongly suggests that we can get the elements of a list using `[[` (double square brackets):
```{r double-square-first}
thing[[1]]
```
```{r double-square-second}
thing[[2]]
```
```{r double-square-third}
thing[[3]]
```
Let's have a look at the types of those three values:
```{r double-square-elements-first}
typeof(thing[[1]])
```
```{r double-square-elements-second}
typeof(thing[[2]])
```
```{r double-square-elements-third}
typeof(thing[[3]])
```
That seems sensible.
Now,
what do we get if we index single square brackets `[…]`?
```{r single-square-value}
thing[1]
```
That looks like a list, not a vector—let's check:
```{r single-square-typeof}
typeof(thing[1])
```
This shows the difference between `[[` and `[`:
the former peels away a layer of data structure, returning only the sub-structure,
while the latter gives us back a structure of the same type as the thing being indexed.
Since a "scalar" is just a vector of length 1,
there is no difference between `[[` and `[` when they are applied to vectors:
```{r single-and-double-1}
v <- c("first", "second", "third")
v[2]
```
```{r single-and-double-2}
typeof(v[2])
```
```{r single-and-double-3}
v[[2]]
```
```{r single-and-double-4}
typeof(v[[2]])
```
> **Flattening and Recursive Indexing**
>
> If a list is just a vector of objects, why do we need the function `list`?
> Why can't we create a list with `c("first", c(2, 20, 200), 30)`?
> The answer is that R flattens the arguments to `c`,
> so that `c(c(1, 2), c(3, 4))` produces `c(1, 2, 3, 4)`.
> It also does automatic type conversion:
> `c("first", c(2, 20, 200), 30)` produces a vector of character strings
> `c("first", "2", "20", "200", "30")`.
> This is helpful once you get used to it
> (which once again is true of both quantum mechanics and necromancy).
>
> Another "helpful, ish" behavior is that using `[[` with a list subsets recursively:
> if `thing <- list(a = list(b = list(c = list(d = 1))))`,
> then `thing[[c("a", "b", "c", "d")]]` selects the 1.
## How can I access elements by name?
R allows us to name the elements in vectors and lists:
if we assign `c(one = 1, two = 2, three = 3)` to `names`,
then `names["two"]` is 2.
We can use this to create a lookup table:
```{r lookup-table}
values <- c("m", "f", "nb", "f", "f", "m", "m")
lookup <- c(m = "Male", f = "Female", nb = "Non-binary")
lookup[values]
```
If the structure in question is a list rather than an atomic vector of numbers, characters, or logicals,
we can use the syntax `lookup$m` instead of `lookup["m"]`:
```{r lookup-list}
lookup_list <- list(m = "Male", f = "Female", nb = "Non-binary")
lookup_list$m
```
We will explore this in more detail when we look at the tidyverse in Chapter \@ref(tidyverse),
since that is where access-by-name is used most often.
For now,
simply note that if the name of an element isn't a legal variable name,
we have to put it in backward quotes to use it with `$`:
```{r quoted-names}
another_list <- list("first field" = "F", "second field" = "S")
another_list$`first field`
```
> If you have control,
> or at least the illusion thereof,
> choose names such as `first_field` that don't require back-quoting.
## How can I create and index a matrix?
Matrices are frequently used in statistics, so R provides built-in support for them.
After `a <- matrix(1:9, nrow = 3)`,
`a` is a 3x3 matrix containing the values 1 through 9:
```{r matrix-order}
a <- matrix(1:9, nrow = 3)
a
```
Behind the scenes,
a matrix is a vector with an [attribute](glossary.html#attribute) called `dim` that stores its dimensions:
```{r matrix-attribute}
dim(a)
```
`a[3, 3]` is a vector of length 1 containing the value 9 (again, "scalars" in R are actually vectors),
while `a[1,]` is the vector `c(1, 4, 7)` (because we are selecting the first row of the matrix)
and `a[,1]` is the vector `c(1, 2, 3)` (because we are selecting the first column of the matrix).
Elements can still be accessed using a single index,
which returns the value from that location in the underlying vector:
```{r matrix-single-index}
a[8]
```
## How do I choose and repeat things?
We cherish the illusion of free will so much that we embed a pretense of it in our machines
in the form of conditional statements using `if` and `else`.
(Ironically,
we then instruct those same machines to make the same decisions over and over.
It's no wonder they sometimes appear mad…)
For example,
here is a snippet of Python that uses `for` and `if` to display
the signs of the numbers in a list:
```{python py-loop-cond}
values = [-15, 0, 15]
for v in values:
if v < 0:
pos_neg = -1
elif v == 0:
pos_neg = 0
else:
pos_neg = 1
print("The pos_neg of", v, "is", pos_neg)
print("The final value of v is", v)
```
Its direct translation into R is:
```{r r-loop-cond}
values <- c(-15, 0, 15)
for (v in values) {
if (v < 0) {
pos_neg <- -1
}
else if (v == 0) {
pos_neg <- 0
}
else {
pos_neg <- 1
}
print(glue::glue("The sign of {v} is {pos_neg}"))
}
print(glue::glue("The final value of v is {v}"))
```
There are a few things to note here:
1. The parentheses in the loop header are required:
we cannot simply write `for v in values`.
1. The curly braces around the body of the loop
and around the bodies of the conditional branches are optional,
since each contains only a single statement.
However, they should always be there to help readability.
1. As in Python,
the loop variable `v` persists after the loop is over.
1. `glue::glue` (the function `glue` from the library of the same name)
interpolates variables into strings in sensible ways.
We will load this library and use plain old `glue` in the explanations that follow.
(Note that R uses `::` to get functions out of packages rather than Python's `.`.)
1. We have called our temporary variable `pos_neg` rather than `sign`
so that we don't accidentally overwrite the rather useful built-in R function
with the latter name.
[Name collisions](glossary.html#name-collision) of this sort
are just as easy in R as they are in Python.
## How can I vectorize loops and conditionals?
The example above is *not* how we should write R:
everything in that snippet can and should be vectorized.
The simplest way to do this is to use the aforementioned built-in function:
```{r using-sign}
print(sign(values))
print(glue::glue("The sign of {values} is {sign(values)}"))
```
But what if the function we want doesn't exist
(or if we don't know what it's called)?
In that case,
the easiest approach is often to create a new vector
whose values are derived from those of the vector we had
and trust R to match up corresponding elements:
```{r using-case-when}
pos_neg <- dplyr::case_when(
values < 0 ~ -1,
values == 0 ~ 0,
values > 0 ~ 1
)
print(glue::glue("The sign of {values} is {pos_neg}"))
```
This solution makes use of `case_when`,
which is a vectorized analog of `if`/`else if`/`else`.
Each branch uses the `~` operator to combine
a Boolean test on the left with a result on the right.
We will see other uses for `~` in subsequent chapters.
## How can I express a range of values?
`for` in R loops over the values in a vector, just as it does in Python.
If we want to loop over the indices instead,
we can use the function `seq_along`:
```{r loop-range}
colors <- c("eburnean", "glaucous", "squamous", "wenge")
for (i in seq_along(colors)) {
print(glue("The length of color {i} is {length(colors[i])}"))
}
```
This output makes no sense until we remember that every value is a vector,
and that `length` returns the length of a vector,
so that `length(colors[0])` is telling us that `colors[0]` contains one element.
If we want the number of characters in the strings,
we can use R's built-in `nchar` or the more modern function `stringr::str_length`:
```{r loop-range-str-length}
for (i in seq_along(colors)) {
print(glue("The length of color {i} is {stringr::str_length(colors[i])}"))
}
```
As you may already have guessed,
`seq_along` returns a vector containing a sequence of integers:
```{r seq-along}
seq_along(colors)
```
Since sequences of this kind are used frequently,
R lets us write them using [range expressions](glossary.html#range-expression):
```{r range-expression}
5:10
```
Their most common use is as indices to vectors:
```{r range-subscript}
colors[2:3]
```
We can similarly subtract a range of colors by index:
```{r negative-range-subscript}
colors[-1:-2]
```
However, R does not allow tripartite expressions of the form `start:end:step`.
For that,
we must use `seq`:
```{r seq-function}
seq(1, 10, 3)
```
This example also shows that ranges in R are inclusive at both ends,
i.e.,
they run up to *and including* the upper bound.
As is traditional among programming language advocates,
people claim that this is more natural
and then cite some supportive anecdote as if it were proof.
> **Repeating Things**
>
> The function `rep` repeats things, so `rep("a", 3)` is `c("a", "a", "a")`.
> If the second argument is a vector of the same length as the first,
> it specifies how many times each item in the first vector is to be repeated:
> `rep(c("a", "b"), c(2, 3))` is `c("a", "a", "b", "b", "b")`.
## How can I use a vector in a conditional statement?
We cannot use a vector directly as a condition in an `if` statement:
```{r vector-cond-fail, error=TRUE}
numbers <- c(0, 1, 2)
if (numbers) {
print("This should not work.")
}
```
Instead,
we must collapse the vector into a single logical value:
```{r all-cond}
numbers <- c(0, 1, 2)
if (all(numbers >= 0)) {
print("This, on the other hand, should work.")
}
```
The function `all` returns `TRUE` if every element in its argument is `TRUE`;
it corresponds to a logical "and" of all its inputs.
We can use a corresponding function `any` to check if at least one value is `TRUE`,
which corresponds to a logical "or" across the whole input.
## How do I create and call functions?
As we have already seen,
we call functions in R much as we do in Python:
```{r func-call}
max(1, 3, 5) + min(1, 3, 5)
```
We define a new function using the `function` keyword.
This creates the function;
to name it,
we must assign the newly-created function to a variable:
```{r func-def}
swap <- function(pair) {
c(pair[2], pair[1])
}
swap(c("left", "right"))
```
As this example shows,
the result of a function is the value of the last expression evaluated within it.
A function can return a value earlier using the `return` function;
we can use `return` for the final value as well,
but most R programmers do not.
```{r func-return}
swap <- function(pair) {
if (length(pair) != 2) {
return(NULL) # This is very bad practice.
}
c(pair[2], pair[1])
}
swap(c("one"))
```
```{r call-swap}
swap(c("left", "right"))
```
Returning `NULL` when our function's inputs are invalid as we have done above is foolhardy,
as doing so means that `swap` can fail without telling us that it has done so.
Consider:
```{r element-of-null}
NULL[1] # Try to access an element of the vector that does not exist.
```
```{r silent-failure}
values <- 5:10 # More than two values.
result <- swap(values) # Attempting to swap the values produces NULL.
result[1] # But we can operate on the result without error.
```
We will look at what we should do instead in Chapter \@ref(testerror).
## How can I write a function that takes variable arguments?
If the number of arguments given to a function is not the number expected,
R complains:
```{r wrong-number-of-args, error=TRUE}
swap("one", "two", "three")
```
(Note that we are passing three separate values here,
not a single vector containing three values.)
If we want a function to handle a [varying number of arguments](glossary.html#variable-arguments),
we represent the "extra" arguments with an ellipsis `...` (three dots),
which serves the same purpose as Python's `*args`:
```{r dot-args}
print_with_title <- function(title, ...) {
print(glue("=={title}=="), paste(..., sep = "\n"))
}
print_with_title("to-do", "Monday", "Tuesday", "Wednesday")
```
> The function `paste` creates a string by combining its arguments with the specified separator.
R uses a special data structure to represent the extra arguments in `...`.
If we want to work with those arguments one by one,
we must explicitly convert `...` to a list:
```{r dot-args-convert}
add <- function(...) {
result <- 0
for (value in list(...)) {
result <- result + value
}
result
}
add(1, 3, 5, 7)
```
## How can I provide default values for arguments?
Like Python and most other modern programming languages,
R lets us define default values for arguments and then pass arguments by name:
```{r define-defaults}
example <- function(first, second = "second", third = "third") {
print(glue("first='{first}' second='{second}' third='{third}'"))
}
example("with just first")
example("with first and second by position", "positional")
example("with first and third by name", third = "by name")
```
One caution:
when you use a name in a function call,
R ignores things that *aren't* functions when looking up the function.
This means that
the call to `orange()` in the code below produces 110 rather than an error
because `purple(purple)` is interpreted as
"pass the value 10 into the globally-defined function `purple`"
rather than "try to call a function `10(10)`":
```{r non-functions-in-call}
purple <- function(x) x + 100
orange <- function() {
purple <- 10
purple(purple)
}
orange()