forked from CerebralMastication/R-Cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_SomeBasics.Rmd
1536 lines (1150 loc) · 48.5 KB
/
02_SomeBasics.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
```{r include=FALSE, cache=FALSE}
set.seed(42)
options(digits = 3)
library(tidyverse)
library(knitr)
knitr::opts_chunk$set(
comment = "#>",
messages = FALSE,
collapse = TRUE,
out.width = "85%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6, dplyr.print_max = 6)
# hook_output <- knit_hooks$get("output")
# knit_hooks$set(output = function(x, options) {
# lines <- options$output.lines
# if (is.null(lines)) {
# return(hook_output(x, options)) # pass to default hook
# }
# x <- unlist(strsplit(x, "\n"))
# more <- "etc ..."
# if (length(lines)==1) { # first n lines
# if (length(x) > lines) { # truncate the output, but add ....
# x <- c(head(x, lines), more)
# }
# } else {
# x <- c(more, x[lines], more)
# }
# # paste these lines together
# x <- paste(c(x, ""), collapse = "\n")
# hook_output(x, options)
# })
```
```{r include=FALSE, cache=FALSE}
set.seed(42)
options(digits = 3)
library(tidyverse)
library(knitr)
knitr::opts_chunk$set(
comment = "#>",
messages = FALSE,
collapse = TRUE,
out.width = "85%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6, dplyr.print_max = 6)
# hook_output <- knit_hooks$get("output")
# knit_hooks$set(output = function(x, options) {
# lines <- options$output.lines
# if (is.null(lines)) {
# return(hook_output(x, options)) # pass to default hook
# }
# x <- unlist(strsplit(x, "\n"))
# more <- "etc ..."
# if (length(lines)==1) { # first n lines
# if (length(x) > lines) { # truncate the output, but add ....
# x <- c(head(x, lines), more)
# }
# } else {
# x <- c(more, x[lines], more)
# }
# # paste these lines together
# x <- paste(c(x, ""), collapse = "\n")
# hook_output(x, options)
# })
```
```{r include=FALSE, cache=FALSE}
set.seed(42)
options(digits = 3)
library(tidyverse)
library(knitr)
knitr::opts_chunk$set(
comment = "#>",
messages = FALSE,
collapse = TRUE,
out.width = "85%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6, dplyr.print_max = 6)
# hook_output <- knit_hooks$get("output")
# knit_hooks$set(output = function(x, options) {
# lines <- options$output.lines
# if (is.null(lines)) {
# return(hook_output(x, options)) # pass to default hook
# }
# x <- unlist(strsplit(x, "\n"))
# more <- "etc ..."
# if (length(lines)==1) { # first n lines
# if (length(x) > lines) { # truncate the output, but add ....
# x <- c(head(x, lines), more)
# }
# } else {
# x <- c(more, x[lines], more)
# }
# # paste these lines together
# x <- paste(c(x, ""), collapse = "\n")
# hook_output(x, options)
# })
```
```{r include=FALSE, cache=FALSE}
set.seed(42)
options(digits = 3)
library(tidyverse)
library(knitr)
knitr::opts_chunk$set(
comment = "#>",
messages = FALSE,
collapse = TRUE,
out.width = "85%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6, dplyr.print_max = 6)
# hook_output <- knit_hooks$get("output")
# knit_hooks$set(output = function(x, options) {
# lines <- options$output.lines
# if (is.null(lines)) {
# return(hook_output(x, options)) # pass to default hook
# }
# x <- unlist(strsplit(x, "\n"))
# more <- "etc ..."
# if (length(lines)==1) { # first n lines
# if (length(x) > lines) { # truncate the output, but add ....
# x <- c(head(x, lines), more)
# }
# } else {
# x <- c(more, x[lines], more)
# }
# # paste these lines together
# x <- paste(c(x, ""), collapse = "\n")
# hook_output(x, options)
# })
```
# Some Basics {#SomeBasics}
Introduction {-#intro-SomeBasics}
------------
The recipes in this chapter lie somewhere between problem-solving ideas
and tutorials. Yes, they solve common problems, but the Solutions
showcase common techniques and idioms used in most R code, including the
code in this cookbook. If you are new to R, we suggest skimming this
chapter to acquaint yourself with these idioms.
Printing Something to the Screen {#recipe-id017}
------------------
### Problem {-#problem-id017}
You want to display the value of a variable or expression.
### Solution {-#solution-id017}
If you simply enter the variable name or expression at the command
prompt, R will print its value. Use the `print` function for generic
printing of any object. Use the `cat` function for producing custom
formatted output.
### Discussion {-#discussion-id017}
It’s very easy to ask R to print something: just enter it at the command
prompt:
``` {r}
pi
sqrt(2)
```
When you enter expressions like that, R evaluates the expression and
then implicitly calls the `print` function. So the previous example is
identical to this:
``` {r}
print(pi)
print(sqrt(2))
```
The beauty of `print` is that it knows how to format any R value for
printing, including structured values such as matrices and lists:
``` {r}
print(matrix(c(1, 2, 3, 4), 2, 2))
print(list("a", "b", "c"))
```
This is useful because you can always view your data: just `print` it.
You need not write special printing logic, even for complicated data
structures.
The `print` function has a significant limitation, however: it prints
only one object at a time. Trying to `print` multiple items gives this
mind-numbing error message:
``` {r, error = TRUE}
print("The zero occurs at", 2 * pi, "radians.")
```
The only way to `print` multiple items is to print them one at a time,
which probably isn’t what you want:
``` {r}
print("The zero occurs at")
print(2 * pi)
print("radians")
```
The `cat` function is an alternative to `print` that lets you concatenate multiple items into a continuous output:
``` {r}
cat("The zero occurs at", 2 * pi, "radians.", "\n")
```
Notice that `cat` puts a space between each item by default. You must
provide a newline character (`\n`) to terminate the line.
The `cat` function can print simple vectors, too:
``` {r}
fib <- c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
cat("The first few Fibonacci numbers are:", fib, "...\n")
```
Using `cat` gives you more control over your output, which makes it
especially useful in R scripts that generate output consumed by others. A serious limitation, however, is that
it cannot print compound data structures such as matrices and lists.
Trying to `cat` them only produces another mind-numbing message:
``` {r, error = TRUE}
cat(list("a", "b", "c"))
```
### See Also {-#see_also-id017}
See Recipe \@ref(recipe-id036), ["Printing Fewer Digits"](#recipe-id036), for controlling output format.
Setting Variables {#recipe-id016}
-----------------
### Problem {-#problem-id016}
You want to save a value in a variable.
### Solution {-#solution-id016}
Use the assignment operator (`<-`). There is no need to declare your
variable first:
``` {r}
x <- 3
```
### Discussion {-#discussion-id016}
Using R in “calculator mode” gets old pretty fast. Soon you will want to
define variables and save values in them. This reduces typing, saves
time, and clarifies your work.
There is no need to declare or explicitly create variables in R. Just
assign a value to the name and R will create the variable:
``` {r}
x <- 3
y <- 4
z <- sqrt(x^2 + y^2)
print(z)
```
Notice that the assignment operator is formed from a less-than character
(`<`) and a hyphen (`-`) with no space between them.
When you define a variable at the command prompt like this, the variable
is held in your workspace. The workspace is held in the computer’s main
memory but can be saved to disk. The variable
definition remains in the workspace until you remove it.
R is a *dynamically typed language*, which means that we can change a
variable’s data type at will. We could set `x` to be numeric, as just
shown, and then turn around and immediately overwrite that with (say) a
vector of character strings. R will not complain:
``` {r}
x <- 3
print(x)
x <- c("fee", "fie", "foe", "fum")
print(x)
```
In some R functions you will see assignment statements that use the
strange-looking assignment operator `<<-`:
``` {r}
x <<- 3
```
That forces the assignment to a global variable rather than a local
variable. Scoping is a bit, well, out of scope for this discussion, however.
In the spirit of full disclosure, we will reveal that R also supports two
other forms of assignment statements. A single equals sign (`=`) can be
used as an assignment operator. A rightward
assignment operator (`->`) can be used anywhere the leftward assignment
operator (`<-`) can be used (but with the arguments reversed):
```{r}
foo <- 3
print(foo)
```
```{r}
5 -> fum
print(fum)
```
We recommend that you avoid these as well. The equals-sign assignment is easily confused with the test for
equality. The rightward assignment can be useful in certain contexts, but it can be confusing to those not used to seeing it.
### See Also {-#see_also-id016}
See Recipe \@ref(recipe-id075), ["Deleting Variables"](#recipe-id075), \@ref(recipe-id025), ["Avoiding Some Common Mistakes"](#recipe-id025), and \@ref(recipe-id009), ["Saving Your Workspace"](#recipe-id009).
See also the help page for the `assign` function.
Listing Variables {#recipe-id091}
-----------------
### Problem {-#problem-id091}
You want to know what variables and functions are defined in your
workspace.
### Solution {-#solution-id091}
Use the `ls` function. Use `ls.str` for more details about each
variable. You can also see your variables and functions in the Environment pane in RStudio, shown in Figure \@ref(fig:environmentPanel).
### Discussion {-#discussion-id091}
The `ls` function displays the names of objects in your workspace:
```{r, echo=FALSE, results='hide'}
rm(list = ls())
```
``` {r}
x <- 10
y <- 50
z <- c("three", "blind", "mice")
f <- function(n, p) sqrt(p * (1 - p) / n)
ls()
```
Notice that `ls` returns a vector of character strings in which each
string is the name of one variable or function. When your workspace is
empty, `ls` returns an empty vector, which produces this puzzling
output:
```{r, echo=FALSE, results='hide'}
rm(list = ls())
```
``` {r}
ls()
```
That is R’s quaint way of saying that `ls` returned a zero-length vector
of strings; that is, it returned an empty vector because nothing is
defined in your workspace.
If you want more than just a list of names, try `ls.str`; this will also
tell you something about each variable:
``` {r}
x <- 10
y <- 50
z <- c("three", "blind", "mice")
f <- function(n, p) sqrt(p * (1 - p) / n)
ls.str()
```
The function is called `ls.str` because it is both listing your
variables and applying the `str` function to them, showing their
structure (see Recipe @ref(recipe-id202), ["Revealing the Structure of an Object"](#recipe-id202)).
Ordinarily, `ls` does not return any name that begins with a dot (`.`).
Such names are considered hidden and are not normally of interest to
users. (This mirrors the Unix convention of not listing files whose
names begin with a dot.) You can force `ls` to list everything by setting
the `all.names` argument to `TRUE`:
``` {r}
ls()
ls(all.names = TRUE)
```
The Environment pane in RStudio also hides objects with names that begin with a dot.
### See Also {-#see_also-id091}
See Recipe \@ref(recipe-id075), ["Deleting Variables"](#recipe-id075), for deleting variables and
Recipe \@ref(recipe-id202), ["Revealing the Structure of an Object"](#recipe-id202), for inspecting your variables.
Deleting Variables {#recipe-id075}
------------------
### Problem {-#problem-id075}
You want to remove unneeded variables or functions from your workspace
or to erase its contents completely.
### Solution {-#solution-id075}
Use the `rm` function.
### Discussion {-#discussion-id075}
Your workspace can get cluttered quickly. The `rm` function removes,
permanently, one or more objects from the workspace:
``` {r, error=TRUE}
x <- 2 * pi
x
rm(x)
x
```
There is no “undo”; once the variable is gone, it’s gone.
You can remove several variables at once:
``` {r, eval=FALSE}
rm(x, y, z)
```
You can even erase your entire workspace at once. The `rm` function has
a `list` argument consisting of a vector of names of variables to
remove. Recall that the `ls` function returns a vector of variables
names; hence, you can combine `rm` and `ls` to erase everything:
``` {r, echo=FALSE, results='hide'}
x <- 10
y <- 50
z <- c("three", "blind", "mice")
f <- function(n, p) sqrt(p * (1 - p) / n)
```
``` {r}
ls()
rm(list = ls())
ls()
```
Alternatively you could click the broom icon at the top of the Environment pane in RStudio, shown in Figure \@ref(fig:environmentPanel).
```{r environmentPanel, fig.cap='Environment pane in RStudio', echo=FALSE, eval=TRUE}
knitr::include_graphics("images_v2/environment.png")
```
Never put `rm(list=ls())` into code you share with others, such as a
library function or sample code sent to a mailing list or Stack Overflow. Deleting all the
variables in someone else’s workspace is worse than rude and will make
you extremely unpopular.
### See Also {-#see_also-id075}
See Recipe \@ref(recipe-id091), ["Listing Variables"](#recipe-id091).
Creating a Vector {#recipe-id038}
-----------------
### Problem {-#problem-id038}
You want to create a vector.
### Solution {-#solution-id038}
Use the `c(...)` operator to construct a vector from given values.
### Discussion {-#discussion-id038}
Vectors are a central component of R, not just another data structure. A
vector can contain either numbers, strings, or logical values, but not a
mixture.
The `c(...)` operator can construct a vector from simple elements:
``` {r}
c(1, 1, 2, 3, 5, 8, 13, 21)
c(1 * pi, 2 * pi, 3 * pi, 4 * pi)
c("My", "twitter", "handle", "is", "@cmastication")
c(TRUE, TRUE, FALSE, TRUE)
```
If the arguments to `c(...)` are themselves vectors, it flattens them
and combines them into one single vector:
``` {r}
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
c(v1, v2)
```
Vectors cannot contain a mix of data types, such as numbers and strings.
If you create a vector from mixed elements, R will try to accommodate
you by converting one of them:
``` {r}
v1 <- c(1, 2, 3)
v3 <- c("A", "B", "C")
c(v1, v3)
```
Here, the user tried to create a vector from both numbers and strings. R
converted all the numbers to strings before creating the vector, thereby
making the data elements compatible. Note that R does this without warning or complaint.
Technically speaking, two data elements can coexist in a vector only if
they have the same mode. The modes of `3.1415` and `"foo"` are `numeric`
and `character`, respectively:
``` {r}
mode(3.1415)
mode("foo")
```
Those modes are incompatible. To make a vector from them, R converts
`3.1415` to `character` mode so it will be compatible with `"foo"`:
``` {r}
c(3.1415, "foo")
mode(c(3.1415, "foo"))
```
> **Warning**
>
> `c` is a generic operator, which means that it works with many
> data types and not just vectors. However, it might not do exactly what
> you expect, so check its behavior before applying it to other
> data types and objects.
### See Also {-#see_also-id038}
See the introduction to Chapter \ref@(DataStructures) for more about vectors and other data structures.
Computing Basic Statistics {#recipe-id101}
--------------------------
### Problem {-#problem-id101}
You want to calculate basic statistics: mean, median, standard
deviation, variance, correlation, or covariance.
### Solution {-#solution-id101}
Use one of these functions, assuming that `x` and `y` are
vectors:
- `mean(x)`
- `median(x)`
- `sd(x)`
- `var(x)`
- `cor(x, y)`
- `cov(x, y)`
### Discussion {-#discussion-id101}
When you first use R you might open the documentation and begin searching for
material entitled “Procedures for Calculating Standard Deviation.” It seems that such an important topic would likely require a whole chapter.
It’s not that complicated.
Standard deviation and other basic statistics are calculated by simple
functions. Ordinarily, the function argument is a vector of numbers and
the function returns the calculated statistic:
``` {r}
x <- c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
mean(x)
median(x)
sd(x)
var(x)
```
The `sd` function calculates the sample standard deviation, and `var`
calculates the sample variance.
The `cor` and `cov` functions can calculate the correlation and
covariance, respectively, between two vectors:
``` {r}
x <- c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
y <- log(x + 1)
cor(x, y)
cov(x, y)
```
All these functions are picky about values that are not available (NA).
Even one NA value in the vector argument causes any of these functions
to return NA or even halt altogether with a cryptic error:
``` {r, error=TRUE}
x <- c(0, 1, 1, 2, 3, NA)
mean(x)
sd(x)
```
It’s annoying when R is that cautious, but it is appropriate.
You must think carefully about your situation. Does an NA in your data
invalidate the statistic? If yes, then R is doing the right thing. If
not, you can override this behavior by setting `na.rm=TRUE`, which tells
R to ignore the NA values:
``` {r}
x <- c(0, 1, 1, 2, 3, NA)
sd(x, na.rm = TRUE)
```
In older versions of R, `mean` and `sd` were smart about data
frames. They understood that each column of the data frame is a
different variable, so they calculated their statistic for each column
individually. This is no longer the case and, as a result, you may read confusing comments online or in older books (like the first edition of this book). In order to apply the functions to each column of a data frame we now need to use a helper function. The tidyverse family of helper functions for this sort of thing is in the `purrr` package. As with other tidyverse packages, this gets loaded when you run `library(tidyverse)`. The function we'll use to apply a function to each column of a data frame is `map_dbl`:
``` {r}
data(cars)
map_dbl(cars, mean)
map_dbl(cars, sd)
map_dbl(cars, median)
```
Notice in this example that `mean` and `sd` each return two values, one for each column defined by the data frame. (Technically, they return a two-element vector whose `names` attribute is taken from the columns of the data frame.)
The `var` function understands data frames without the help of a mapping function. It calculates the covariance between the columns of the data frame and returns the covariance matrix:
``` {r}
var(cars)
```
Likewise, if `x` is either a data frame or a matrix, then `cor(x)`
returns the correlation matrix and `cov(x)` returns the covariance
matrix:
``` {r}
cor(cars)
cov(cars)
```
### See Also {-#see_also-id101}
See Recipes \@ref(recipe-id025), ["Avoiding Some Common Mistakes"](#recipe-id025), \@ref(recipe-id057), ["Applying a Function to Every Column"](#recipe-id157), and \@ref(recipe-id132), ["Testing a Correlation for Significance"](#recipe-id132).
Creating Sequences {#recipe-id021}
------------------
### Problem {-#problem-id021}
You want to create a sequence of numbers.
### Solution {-#solution-id021}
Use an `n:m` expression to create the simple sequence *n*, *n*+1, *n*+2, ..., *m*:
``` {r}
1:5
```
Use the `seq` function for sequences with an increment other than 1:
``` {r}
seq(from = 1, to = 5, by = 2)
```
Use the `rep` function to create a series of repeated values:
``` {r}
rep(1, times = 5)
```
### Discussion {-#discussion-id021}
The colon operator (`n:m`) creates a vector containing the sequence *n*,
*n*+1, *n*+2, ..., *m*:
``` {r}
0:9
10:19
9:0
```
R was clever with the last expression (`9:0`). Because 9 is
larger than 0, it counts backward from the starting to ending value. You can also use the colon operator directly with the pipe to pass data to another function:
```{r eval=FALSE}
10:20 %>% mean()
```
The colon operator works for sequences that grow by 1 only. The `seq`
function also builds sequences but supports an optional third argument,
which is the increment:
``` {r}
seq(from = 0, to = 20)
seq(from = 0, to = 20, by = 2)
seq(from = 0, to = 20, by = 5)
```
Alternatively, you can specify a length for the output sequence and then
R will calculate the necessary increment:
``` {r}
seq(from = 0, to = 20, length.out = 5)
seq(from = 0, to = 100, length.out = 5)
```
The increment need not be an integer. R can create sequences with
fractional increments, too:
``` {r}
seq(from = 1.0, to = 2.0, length.out = 5)
```
For the special case of a “sequence” that is simply a repeated value, you
should use the `rep` function, which repeats its first argument:
``` {r}
rep(pi, times = 5)
```
### See Also {-#see_also-id021}
See Recipe \@ref(recipe-id047), ["Creating a Sequence of Dates"](#recipe-id047), for creating a sequence of `Date` objects.
Comparing Vectors {#recipe-id020}
-----------------
### Problem {-#problem-id020}
You want to compare two vectors, or you want to compare an entire vector
against a scalar.
### Solution {-#solution-id020}
The comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`) can perform
an element-by-element comparison of two vectors. They can also compare a
vector’s element against a scalar. The result is a vector of logical
values in which each value is the result of one element-wise comparison.
### Discussion {-#discussion-id020}
R has two logical values, `TRUE` and `FALSE`. These are often called
*Boolean* values in other programming languages.
The comparison operators compare two values and return `TRUE` or
`FALSE`, depending upon the result of the comparison:
``` {r}
a <- 3
a == pi # Test for equality
a != pi # Test for inequality
a < pi
a > pi
a <= pi
a >= pi
```
You can experience the power of R by comparing entire vectors at once. R
will perform an element-by-element comparison and return a vector of
logical values, one for each comparison:
``` {r}
v <- c(3, pi, 4)
w <- c(pi, pi, pi)
v == w # Compare two 3-element vectors
v != w
v < w
v <= w
v > w
v >= w
```
You can also compare a vector against a single scalar, in which case R
will expand the scalar to the vector’s length and then perform the
element-wise comparison. The previous example can be simplified in this
way:
``` {r}
v <- c(3, pi, 4)
v == pi # Compare a 3-element vector against one number
v != pi
```
(This is an application of the Recycling Rule discussed in Recipe \@ref(recipe-id050), ["Understanding the Recycling Rule"](#recipe-id050).)
After comparing two vectors, you often want to know whether *any* of the
comparisons were true or whether *all* the comparisons were true. The
`any` and `all` functions handle those tests. They both test a logical
vector. The `any` function returns `TRUE` if any element of the vector
is `TRUE`. The `all` function returns `TRUE` if all elements of the
vector are `TRUE`:
``` {r}
v <- c(3, pi, 4)
any(v == pi) # Return TRUE if any element of v equals pi
all(v == 0) # Return TRUE if all elements of v are zero
```
### See Also {-#see_also-id020}
See Recipe \@ref(recipe-id039), ["Selecting Vector Elements"](#recipe-id039).
Selecting Vector Elements {#recipe-id039}
-------------------------
### Problem {-#problem-id039}
You want to extract one or more elements from a vector.
### Solution {-#solution-id039}
Select the indexing technique appropriate for your problem:
- Use square brackets to select vector elements by their position,
such as `v[3]` for the third element of `v`.
- Use negative indexes to exclude elements.
- Use a vector of indexes to select multiple values.
- Use a logical vector to select elements based on a condition.
- Use names to access named elements.
### Discussion {-#discussion-id039}
Selecting elements from vectors is another powerful feature of R. Basic
selection is handled just as in many other programming languages—use
square brackets and a simple index:
``` {r}
fib <- c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
fib
fib[1]
fib[2]
fib[3]
fib[4]
fib[5]
```
Notice that the first element has an index of 1, not 0 as in some other
programming languages.
A cool feature of vector indexing is that you can select multiple
elements at once. The index itself can be a vector, and each element of
that indexing vector selects an element from the data vector:
``` {r}
fib[1:3] # Select elements 1 through 3
fib[4:9] # Select elements 4 through 9
```
An index of 1:3 means select elements 1, 2, and 3, as just shown. The
indexing vector needn’t be a simple sequence, however. You can select
elements anywhere within the data vector—as in this example, which
selects elements 1, 2, 4, and 8:
``` {r}
fib[c(1, 2, 4, 8)]
```
R interprets negative indexes to mean *exclude* a value. An index of –1,
for instance, means exclude the first value and return all other values:
``` {r}
fib[-1] # Ignore first element
```
You can extend this method to exclude whole slices by using an indexing
vector of negative indexes:
``` {r}
fib[1:3] # As before
fib[-(1:3)] # Invert sign of index to exclude instead of select
```
Another indexing technique uses a logical vector to select elements from
the data vector. Everywhere that the logical vector is `TRUE`, an
element is selected:
``` {r}
fib < 10 # This vector is TRUE wherever fib is less than 10
fib[fib < 10] # Use that vector to select elements less than 10
fib %% 2 == 0 # This vector is TRUE wherever fib is even
fib[fib %% 2 == 0] # Use that vector to select the even elements
```
Ordinarily, the logical vector should be the same length as the data
vector so you are clearly either including or excluding each element.
(If the lengths differ, then you need to understand the Recycling Rule, discussed in Recipe \@ref(recipe-id050), ["Understanding the Recycling Rule"](#recipe-id050).)
By combining vector comparisons, logical operators, and vector indexing,
you can perform powerful selections with very little R code.
Select all elements greater than the median:
```{r}
v <- c(3, 6, 1, 9, 11, 16, 0, 3, 1, 45, 2, 8, 9, 6, -4)
v[ v > median(v)]
```
Select all elements in the lower and upper 5%:
```{r}
v[ (v < quantile(v, 0.05)) | (v > quantile(v, 0.95)) ]
```
The previous example uses the `|` operator, which means "or" when indexing. If you wanted "and," you would use the `&` operator.
Select all elements that exceed ±1 standard deviations from the mean:
```{r}
v[ abs(v - mean(v)) > sd(v)]
```
Select all elements that are neither `NA` nor `NULL`:
```{r}
v <- c(1, 2, 3, NA, 5)
v[!is.na(v) & !is.null(v)]
```
One final indexing feature lets you select elements by name. It assumes
that the vector has a `names` attribute, defining a name for each
element. You can define the names by assigning a vector of character strings to
the attribute:
``` {r}
years <- c(1960, 1964, 1976, 1994)
names(years) <- c("Kennedy", "Johnson", "Carter", "Clinton")
years
```
Once the names are defined, you can refer to individual elements by
name:
``` {r}
years["Carter"]
years["Clinton"]
```
This generalizes to allow indexing by vectors of names; R returns every
element named in the index:
``` {r}
years[c("Carter", "Clinton")]
```
### See Also {-#see_also-id039}
See Recipe \@ref(recipe-id050), ["Understanding the Recycling Rule"](#recipe-id050), for more about the Recycling Rule.
Performing Vector Arithmetic {#recipe-id019}
----------------------------
### Problem {-#problem-id019}
You want to operate on an entire vector at once.
### Solution {-#solution-id019}
The usual arithmetic operators can perform element-wise operations on
entire vectors. Many functions operate on entire vectors, too, and
return a vector result.
### Discussion {-#discussion-id019}
Vector operations are one of R’s great strengths. All the basic
arithmetic operators can be applied to pairs of vectors. They operate in
an element-wise manner; that is, the operator is applied to