-
Notifications
You must be signed in to change notification settings - Fork 3
/
Lab_1_modified.rmd
1132 lines (818 loc) · 53.5 KB
/
Lab_1_modified.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
---
title: "An introduction to `R` for ecological modeling (lab 1)"
author:
- Stephen Ellner, modified by Ben Bolker & Bob Douma.
- Adapted to R Markdown by Alejandro Morales.
date: "October 31, 2022"
output:
bookdown::pdf_book:
includes:
in_header: preamble1.tex
word_document: default
pdf_document: default
html_document:
fig_caption: yes
fig_height: 4.5
fig_width: 5
number_sections: yes
geometry: margin=3cm
fontsize: 11pt
---
```{r setup, include=FALSE}
#knitr:yuh5:opts_chunk$set(echo = TRUE)
#knitr::opts_chunk$set(error = TRUE)
options(tinytex.verbose = TRUE)
if(!requireNamespace("kableExtra")) install.packages("kableExtra")
library(kableExtra)
```
# Learning outcomes
The aim of this tutorial is to learn the basics of `R`. After completing the tutorial you will be able to:
1. Install `R` and associated packages and Rstudio
2. Do interactive calculations in the `R` console
3. Consult the built-in help in `R`
4. Create, modify and run `R` scripts
5. Setup a typical workflow in `R` (loading libraries, reading data, doing statistics and saving results)
6. Work with the most common data types in `R` (vectors, matrices, lists and data frames)
```{r eval=F,echo=F}
setwd("C:/Users/douma002/OneDrive - WageningenUR/Education/CSA-34306 Ecological Models and Data in R/2019-2020/labs/bolker-labs")
```
# How to use this tutorial
* This tutorial contains many sample calculations. It is important to do these yourself---**type them in at your keyboard and see what happens on your screen**---to get the feel of working in `R`.
* **Exercises** in the middle of a section should be done immediately, and make sure you have them rightly solved before moving on. Some other, more challenging, exercises appear at the end of some sections, and these can be left until later.
# What is `R`?
`R` is an object-oriented scripting language that
* can be used for numerical simulation of deterministic and stochastic dynamic models.
* has an extensive set of functions for classical and modern statistical data analysis and modeling.
* has graphics functions for visualizing data and model output
* a user interface with a few basic menus and extensive help facilities
`R` is an open source project, available for free download via the Web. Originally a research project in statistical computing it is now managed by a development team that includes a number of well-regarded statisticians. It is widely used by statistical researchers and a growing number of theoretical ecologists and ecological modelers as a platform for making new methods available to users.
# Installing `R` on your computer: basics
If `R` is already installed on your computer, you can skip this section.
The main source for `R` is the CRAN home page `http://cran.r-project.org`.
You can get the source code, but most users will prefer a precompiled
version. To get one of these from CRAN:
* go to `http://cran.r-project.org/mirrors.html` and find
a mirror site that is geographically somewhat near you.
* Find the appropriate page for your operating system --- when you get to the
download section, go to `base` rather than `contrib`. Download the binary file (e.g. `base/R-x.y.z-win32.exe` for Windows, `R-x.y.z.dmg` for MacOS, where `x.y.z` is the version number). The binary files are large (30--60 megabytes) --- you will need to find a fast internet connection.
* Read and follow the instructions (which are pretty much "click on the icon").
# Installing and using Rstudio
Nowadays programs are available that integrate `R` in a sophisticated way by combining a console, a *syntax highlighting* editor (giving colors to `R` commands and allowing you to identify missing parentheses, quotation marks etc.), tools for plotting, debugging, workspace management and connections to versioning systems into one program. Rstudio is currently the most advanced wrapper around R and is highly recommended if `R` is the core of your work. Rstudio can be found and downloaded at https://www.rstudio.com.
If a new `R` version is launched after you installed Rstudio, you can change the `R` version that is used in Rstudio by clicking on `Tools` and `Global Options`, choose `R general` and select the location of the most recent `R` version.
Rstudio usually displays four panels. The default setting is a script editor at the top-left of the screen, the console at the bottom-left, the global environment (which shows what is stored in the memory) at the top-right, and a plotting region at bottom-right. As you see some panel have multiple tabs that include other useful features such as the help (bottom-right), the (available and loaded) packages (bottom-right) etc.
# The `R` package system
The standard distributions of `R` include several *packages*, user-contributed suites of add-on functions. This lab uses some packages that are not part of the standard distribution. In general, you can install additional packages
from within `R` using the `Packages` menu, or the `install.packages` command.
You may be able to install new packages from a menu within `R`. Type and it will installe the package `ggplot2` that you will use in the next tutorial.
```{r,eval=FALSE,df-drop-2, class.source='bad-code'}
install.packages("ggplot2")
```
(for example --- this installs the `ggplot2` package). You can install more than one package at a time:
```{r,eval=FALSE}
install.packages(c("ggplot2","nlme"))
```
(`c` stands for "combine", and is the command for combining multiple things into a single object.)
Some of the important functions and packages (collections of functions) for statistical modeling and data analysis are summarized in Table 2. Venables and Ripley (2002) give a good practical (although somewhat advanced) overview, and you can find a list of available packages and their contents at CRAN, the main `R` website (http://www.cran.r-project.org --- select a mirror site near you and click on `Package sources`). For the most part, we will not be concerned here with this side of `R`.
```{r, echo = FALSE, results = 'asis'}
data = rbind(c("\\texttt{aov}, \\texttt{anova}", "Analysis of variance or deviance"),
c("\\texttt{lm}", "Linear models (regression, ANOVA, ANCOVA)"),
c("\\texttt{glm}", "Generalized linear models (e.g. logistic, Poisson regression)"),
c("\\texttt{gam}", "Generalized additive models (in package \\texttt{mgcv})"),
c("\\texttt{nls}", "Fit nonlinear models by least-squares"),
c("\\texttt{lme}, \\texttt{nlme},\\texttt{lmer}, \\texttt{glmer}", "Linear, generalized linear, and nonlinear mixed-effects models"),
c("","(repeated measures, block effects, spatial models) in packages"),
c("","\\texttt{nlme} and \\texttt{lme4}"),
c("\\texttt{boot}","Package: bootstrapping functions"),
c("\\texttt{splines}","Package: nonparametric regression (more in packages \\texttt{fields},"),
c("","\\texttt{KernSmooth}, \\texttt{logspline}, \\texttt{sm} and others)"),
c("\\texttt{princomp}, \\texttt{manova}, \\texttt{lda}, \\texttt{cancor}","Multivariate analysis (some in package \\texttt{MASS}; also see packages"),
c("","\\texttt{vegan}, \\texttt{ade4})"),
c("\\texttt{survival}", "Package: survival analysis"),
c("\\texttt{tree}, \\texttt{rpart}","Packages: tree-based regression"))
kable(data, caption = "A few of the functions and packages in `R` for statistical modeling and data analysis. There are \\emph{many} more, but you will have to learn about them somewhere else.", col.names = c("Function","Definition and packages"), format="latex", booktabs=TRUE, escape = F) %>%
kable_styling(latex_options=c("scale_down"))
```
# Interactive calculations in the console
The console is where you enter commands for `R` to execute *interactively*, meaning that the command is executed and the result is displayed as soon as you hit the `Enter` key (bottom-left panel in Rstudio). For example, at the command prompt `>`, type in `2+2` and hit `Enter`; you will see
```{r, echo =FALSE}
2+2
```
To do anything complicated, you have to store the results from calculations by *assigning* them to variables, using `=` or `<-`. For example:
```{r}
a=2+2
```
`R` automatically creates the variable `a` and stores the result (4) in it, but it doesn't print anything. This may seem strange, but you'll often be creating and manipulating huge sets of data that would fill many screens, so the default is to skip printing the results. To ask `R` to print the value, just type the variable name by itself at the command prompt:
```{r}
a
```
(the `[1]` at the beginning of the line is just `R` printing an index of element numbers; if you print a result that displays on multiple lines, `R` will put an index at the beginning of each line. `print(a)` also works to print the value of a variable.) By default, a variable created this way is a *vector*, and it is *numeric* because we gave `R` a number rather than some other type of data (e.g. a character string like `"pxqr"`). In this case `a` is a numeric vector of length 1, which acts just like a number.
You could also type `a=2+2; a`, using a semicolon to put two or more commands on a single line. Conversely, you can break lines *anywhere that `R` can tell you haven't finished your command* and `R` will give you a "continuation" prompt (`+`) to let you know that it doesn't think you're finished yet: try typing
```{r,eval=FALSE}
a=3*(4+ [Enter]
5)
```
to see what happens. You will sometimes see the continuation prompt when you don't expect it, e.g. if you forget to close parentheses.If you get stuck continuing a command you don't want---e.g. you opened the wrong parentheses---just hit the `Escape` key or the stop icon in the menu bar to get out.
Variable names in `R` must begin with a letter, followed by letters or numbers. You can break up long names with a period, as in `very.long.variable.number.3`, or an underscore (`_`), but you can't use blank spaces in variable names (or at least it's not worth the trouble).
Variable names in `R` are case sensitive, so `Abc` and `abc`
are different variables. Make variable names long enough to remember, short
enough to type.`N.per.ha` or `pop.density` are better than `x`
and `y` (too short) or `available.nitrogen.per.hectare` (too long).
Avoid `c`, `l`, `q`, `t`, `C`, `D`, `F`, `I`, and `T`, which are either built-in `R` functions or hard to tell apart.
`R` does calculations with variables as if they were numbers. It uses
`+`, `-`, `*`, `/`, and `^` for addition, subtraction, multiplication, division and exponentiation, respectively. For example:
```{r}
x=5
y=2
z1=x*y ## no output
z2=x/y ## no output
z3=x^y ## no output
z2
z3
```
Even though `R` did not display the values of `x` and `y`, it "remembers" that it assigned values to them. Type `x; y` to display the values.
You can retrieve and edit previous commands. The up-arrow ($\uparrow$) in the console recalls previous commands to the prompt. They also can be found in the top-right tab `History`. For example, you can bring back the second-to-last command and edit it into
```{r}
z3=2*x^y
```
You can combine several operations in one calculation:
```{r}
A=3
C=(A+2*sqrt(A))/(A+5*sqrt(A))
C
```
Parentheses specify the order of operations.
The command
```{r}
C=A+2*sqrt(A)/A+5*sqrt(A)
```
is not the same as the one above; rather, it is equivalent to `C=A + 2*(sqrt(A)/A) + 5*sqrt(A)`.
The default order of operations is: (1) parentheses; (2) exponentiation, or powers, (3) multiplication and division, (4) addition and subtraction.
b = 12-4/2^3 gives 12 - 4/8 = 12 - 0.5 = 11.5
b = (12-4)/2^3 gives 8/8 = 1
b = -1^2 gives -(1^2) = -1
b = (-1)^2 gives 1
In complicated expressions you might start off by *using parentheses to specify explicitly what you want*, such as b = 12 - (4/(2^3))
or at least b = 12 - 4/(2^3); a few extra sets of parentheses never hurt, although when you get confused it's better to think through the order of operations rather than flailing around adding parentheses at random. `R` also has many *built-in mathematical functions* that operate on variables
(Table 1 shows a few).
```{r, echo = FALSE, results = 'asis'}
library(knitr)
data = rbind(c("\\texttt{abs}", "absolute value"),
c("\\texttt{cos, sin, tan}", "cosine, sine, tangent of angle $x$ in radians"),
c("\\texttt{exp}", "exponential function, $e^x$"),
c("\\texttt{log}", "natural (base-$e$) logarithm"),
c("\\texttt{log10}", "common (base-10) logarithm"),
c("\\texttt{sqrt}", "square root"))
kable(data, caption = "Some of the built-in mathematical functions in R. You can get a more complete list from the Help system: \\texttt{?Arithmetic} for simple, \\texttt{?log} for logarithmic, \\texttt{?sin} for trigonometric, and \\texttt{?Special} for special functions.", col.names = c("Function","Definition"), format="latex", booktabs=TRUE, escape = F)
```
```{block2, type = "exercisebox",latex.options="{1}"}
Using editing shortcuts wherever you can, have `R` compute the values of:
1. $\frac{2^7}{2^7 - 1}$ and compare it with $({1 - \frac{1}{2^7}})^{-1}$
2.
* $1+0.2$
* $1+0.2+0.2^2/2 + \cos(2.3)$
* $\log(1)$
* $\exp(0.2)$
3. The standard normal probability density, $\frac{1}{\sqrt(2\pi)}\exp(-x^2/2)$, for values of $x=1$ and $x=2$ (`R` knows $\pi$ as `pi`). You can check your answers against the built-in function for the normal distribution; `dnorm(1)` and `dnorm(2)` should give you the values for the standard normal for $x=1$ and $x=2$.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
1
`(2^7)/(2^7-1)`
#versus
`(1-2^7)^(-1)`
2
`1+0.2`
`1+0.2+0.2^2/2+cos(2.3)`
3
`x <- 1`
`1/sqrt(2*pi)*exp(-x^2/2)`
`x <- 2`
`1/sqrt(2*pi)*exp(-x^2/2)`
```
# The help system
R has a help system, although it is generally better for providing detail or reminding you how to do things than for basic ``how do I ...?'' questions.
* You can get help on any R function by entering
```
?foo
```
Where `foo` is the name of the function you are interested in (e.g., try `?sin`).
* `??topic` or `help.search("topic")`
(with quotes) will list information related to `topic` available in the base system or in any extra installed packages: then use `?topic` to see the information, perhaps using `library(pkg)` to load the appropriate package first. `help.search` uses "fuzzy matching" --- for example,
`help.search("log")` finds 528 entries (on my particular system) including lots of functions with "plot", which includes the letters "lot", which
are *almost* like "log". If you can't stand it, you can turn this behavior off by specifying the incantation `help.search("log",agrep=FALSE)` (81 results which still include matches for "logistic", "myelogenous", and "phylogeny" ...)
* On-line help resources - just google it.
In our experience, the help provided by `R` requires some experience in the `R` language to be able to understand it. Therefore, a general, but practical advice is to google your problem. In 99.9% of the cases someone else had a similar question in the past which were solved by the `R` community. Start you search string with "R-help" helps to filter relevant webpages. Place were you likely will find answers are https://stackoverflow.com or https://stat.ethz.ch.
# Using scripts and data files
Modeling and complicated data analysis are often much easier if you use *scripts*, which are a series of commands stored in a text file. Scripting has a number of advantages and should be standard practice when doing statstics for reasons of transparency (you can see what you have done), repeatability (tomorrow you will get the same result as today) and transferability (a colleague can easily check what you have done and redo your analysis). Even for relatively simple tasks, script files are useful for building up a calculation step-by-step, making sure that each part works before adding on to it. We recommend you making a habit typing all commands in a script editor before sending it the console, otherwise important parts of your analysis may get lost because you did not store them.
Rstudio has an advanced script editor that recognizes `R` syntax by giving different colors to different `R` commands and by automatic completion of parentheses. You can also use Windows Notepad or Wordpad but you **should not** use MS Word.
Most programs for working with models or analyzing data follow a simple pattern of program parts:
1. "Setup" statements. For example, load some packages, or run another script file that
creates some functions (more on functions later).
2. Input some data from a file or the keyboard. For example, read in data from a text file.
3. Carry out the calculations that you want. For example, fit several statistical models to the data and compare them.
4. Print the results, graph them, or save them to a file. For example, graph the results, and save the graph to disk for including in your term project.
To tell `R` where data and script files are located, you can do any one of the following:
* spell out the *path*, or file location, explicitly. (Use
a single forward slash to separate folders (e.g. `"c:/My Documents/R/script.R"`): this works on all platforms.)
* change your working directory to wherever the file(s) are located using the `setwd` (**set** **w**orking **d**irectory) function, e.g. `setwd("c:/temp")` or through clicking on 'Session' and 'set working directory'. Changing your working directory is more efficient in the long run, if you save all the script and data files for a particular project in the same directory and switch to that directory when you start work.
# Typical workflow in `R`: an example using linear regression
To get a feel for a typical workflow in R we'll fit a straight-line model (linear regression) to data.
Start a blank `R` script (File -> New File -> R script) and save it on a convenient location.
Below are some data on the maximum growth rate $r_{max}$ of laboratory populations of the green alga *Chlorella vulgaris* as a function of light intensity ($\mu$E per m$^2$ per second). These experiments were run during the system-design phase of the study reported by Fussman et al. (2000).
Light: 20, 20, 20, 20, 21, 24, 44, 60, 90, 94, 101
$r_{max}$: 1.73, 1.65, 2.02, 1.89, 2.61, 1.36, 2.37, 2.08, 2.69, 2.32, 3.67
To analyze these data in R, first enter them as numerical *vectors* in your script and send them to the console:
```{r}
Light=c(20,20,20,20,21,24,44,60,90,94,101)
rmax=c(1.73,1.65,2.02,1.89,2.61,1.36,2.37,2.08,2.69,2.32,3.67)
```
The function `c` *combines* the individual numbers into a vector. Try recalling (with $\uparrow$) and modifying the above command to
```
Light=20,20,20,20,21,24,44,60,90,94,101
```
and see the error message you get: in order to create a vector of specified numbers, you **must** use the `c` function. Don't be afraid of error messages: the answer to "what would happen if I ...?" is usually "try it and see!"
To see a histogram of the growth rates enter `hist(rmax)`, which opens a graphics window and displays the histogram. There are *many* other built-in statistics functions: for example `mean(rmax)` computes you the mean, and `sd(rmax)` and `var(rmax)` compute the standard deviation and variance, respectively. Play around with these functions, and any others you can think of.
To see how light intensity affects algal rate of increase, type
```{r, eval=FALSE, echo=TRUE}
plot(rmax ~ Light)
```
in the script (and send it the console) to plot `rmax` ($y$) against `Light` ($x$). The `~` sign implies "as a function of". Alternatively, type `plot(Light,rmax)`. A linear regression would seem like a reasonable model for these data. **Don't close this plot window**: we'll soon be adding to it.
```{r,echo=FALSE,fig=TRUE,height=2, fig.cap = "Some of R's graphics parameters. Color specification, `col`, also applies in many other contexts: colors are set to a rainbow scale here. See `?par` for (many more) details on graphics parameters, and one or more of `?rgb`, `?palette`, or `apropos(\"color\")` for more on colors.", fig.height=3.0, fig.width=6}
h = rev((1:6)/6)
xr = seq(0,0.9,length=20)
xpos = 1.2
op = par(xpd=TRUE,mar=c(0,0,0,5))
plot(0:1,range(h),type="n",axes=FALSE,ann=FALSE)
points(xr,rep(h[1],20),pch=1:20)
text(xpos,h[1],"pch: point type",adj=1)
##palette(gray((0:19)/19))
palette(rainbow(20))
points(xr,rep(h[2],20),col=1:20,pch=16)
palette("default")
text(xpos,h[2],"col: point color",adj=1)
points(xr,rep(h[3],20),cex=seq(0.01,2,length=20))
text(xpos,h[3],"cex: point size",adj=1)
text(xr,rep(h[4],20),c(letters[1:5],LETTERS[1:5],0:9))
text(xpos,h[4],"text",adj=1)
##text(seq(0.1,0.9,length=20),rep(0.6,20),letters[1:20],cex=seq(0.01,2,length=20))
nl = 6
nlsp = 0.1
lend = 0.95
##segments(seq(0,0.9,length=nl),rep(h[5],2*nl),
## seq(1/nl,1,length=nl),rep(h[5],2*nl),
## want to go from 0 to lend, in nl segments,
## using a fraction fr of the space for interspaces
## each segment + space takes up lend/nl
##
fr = 0.7
seg1 = seq(0,by=lend/nl,length=nl)
seg2 = seq(lend/nl,to=lend,by=lend/nl)-(lend*(1-fr)/nl)
segments(seg1,rep(h[5],nl),
seg2,
rep(h[5],nl),
lty=1:nl,lwd=3)
text(xpos,h[5],"lty: line type",adj=1)
nv = 10
segments(seq(0,1/(1+nlsp),length=nv),rep(h[6],nv),
seq(0.05,0.95,length=nv),rep(h[6],nv),
lwd=1:10)
text(xpos,h[6],"lwd: line width",adj=1)
par(op)
```
`R`'s default plotting character is an open circle. Open symbols are generally better than closed symbols for plotting because it is easier to see where they overlap, but you could include `pch=16` in the `plot` command if you wanted closed circles instead. Figure 1 shows several more ways to adjust the appearance of lines and points in `R`.
To perform linear regression we create a linear model using the `lm` (**l**inear **m**odel) function:
```{r}
fit = lm(rmax~Light)
```
(Note that linear model is read as "model $r_{max}$ as a function of light".)
The `lm` command produces no output at all, but it creates `fit` as an **object**, i.e. a data structure consisting of multiple parts, holding the results of a regression analysis with `rmax` being modeled as a
function of `Light`. Unlike most statistics packages, R rarely produces automatic summary output from an analysis. Statistical analyses in R are done by creating a model, and then giving additional commands to extract desired information about the model or display results graphically.
To get a summary of the results, enter the command `summary(fit)`. `R` sets up model objects (more on this later) so that the function `summary` "knows" that `fit` was created by `lm`, and produces an appropriate summary of results for an `lm` object:
```{r}
summary(fit)
```
[If you've had (and remember) a statistics course the output will make sense to you. The table of coefficients gives the estimated regression
line as $r_{max} = 1.581 + 0.014 \times Light$, and associated with each coefficient is the standard error of the estimate, the $t$-statistic value for testing whether the coefficient is nonzero, and the $p$-value corresponding to the $t$-statistic. Below the table, the adjusted R-squared gives the estimated fraction of the variance explained by the regression line, and the $p$-value in the last line is an overall test for significance of the model against the null hypothesis that the response variable is independent of the predictors.]
You can add the regression line to the plot of the data with a function taking `fit` as its input (if you closed the plot of the data, you will need to create it again in order to add the regression line):
```{r, eval = FALSE, echo = TRUE}
abline(fit)
```
(`abline`, pronounced "a b line", is a general-purpose function for adding lines to a plot: you can specify horizontal or vertical lines, a slope and an intercept, or a regression model: `?abline`).
```{r,echo=FALSE,fig=TRUE, fig.cap = "Graphical summary of regression analysis", fig.width=4,fig.height=3}
par(mar = c(4,4,0.5,0.5), las = 1)
plot(Light,rmax)
abline(fit)
```
You can get the coefficients by using the `coef` function:
```{r}
coef(fit)
```
You can also "interrogate" `fit` directly. Type `names(fit)` to get a list of the components of `fit`, and then use the `$` symbol to extract components according to their names.
```{r}
names(fit)
```
For more information (perhaps more than you want) about `fit`, use `str(fit)` (for **str**ucture). You can get the regression coefficients this way:
```{r}
fit$coefficients
```
It's good to be able to look inside `R` objects when necessary, but all other things being equal you should prefer (e.g.) `coef(x)` to `x$coefficients`.
Usually data is loaded from a file. To illustrate this, grab `Intro2.R` and `ChlorellaGrowth.txt` from brighspace to see how this is done. In `ChlorellaGrowth.txt` the two variables are entered as columns of a data matrix. Then instead of typing these in by hand, the command
```{r}
X=read.table("ChlorellaGrowth.txt",header=TRUE)
```
reads the file (**from the current directory**) and puts the data values into the variable `X`; `header=TRUE` specifies that the file includes column names. **Note** that as specified above you need to make sure that `R` is looking for the data file in the right place ... either move the data file to your current working directory, or change the line so that it points to the actual location of the data file.
Extract the variables from `X` with the commands
```{r}
Light=X[,1]
rmax=X[,2]
```
Think of these as shorthand for "`Light` = everything in column 1 of `X`", and "`rmax` = everything in column 2 of `X`" (we'll learn about working with data matrices later). From there on out it's the same as before, with some additions that set the axis labels and add a title.
```{block2, type = "exercisebox",latex.options="{1}"}
Make a copy of `Intro2.R` under a new name, and modify the copy so that it does linear regression of algal growth rate on the natural log of light intensity, `LogLight=log(Light)`, and plots the data appropriately. You should end up with a graph that resembles Figure 3.
*Hint:* when you switch from light intensity to log light intensity, the range on your $x$ axis will change and you will have to change the $x$ position at which you plot the growth rate equation.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`X=read.table("ChlorellaGrowth.txt",header=TRUE)`
`Light=X[,1]`
`rmax=X[,2]`
`logLight=log(Light)` # natural logarithm!
`op <- par(cex=1,cex.main=0.9, mar = c(4,4,4,0.5), las = 1)`
`plot(logLight,rmax,
xlab=expression(Log~light~intensity~(mu*E/m^2/s)),
ylab="Maximum growth rate rmax (1/d)",pch=16)
title(main="Data from Fussmann et al. (2000)")`
`fit=lm(rmax~logLight)`
`summary(fit)`
`abline(fit)`
`rcoef=round(coef(fit),digits=3)`
`text(3.7,3.5,paste("rmax=",rcoef[1],"+",rcoef[2],"log(Light)"))`
`par(op)`
```
```{r,echo=FALSE,fig=TRUE,results='hide', fig.cap = "Graphical summary of regression analysis, using log of light intensity (and annotating the plot)", fig.width=4.5,fig.height=4}
X=read.table("ChlorellaGrowth.txt",header=TRUE)
Light=X[,1]
rmax=X[,2]
logLight=log(Light) # natural logarithm!
op <- par(cex=1,cex.main=0.9, mar = c(4,4,4,0.5), las = 1)
plot(logLight,rmax,
xlab=expression(Log~light~intensity~(mu*E/m^2/s)),
ylab="Maximum growth rate rmax (1/d)",pch=16)
title(main="Data from Fussmann et al. (2000)")
fit=lm(rmax~logLight)
summary(fit)
abline(fit)
rcoef=round(coef(fit),digits=3)
text(3.7,3.5,paste("rmax=",rcoef[1],"+",rcoef[2],"log(Light)"))
par(op)
```
```{block2, type = "exercisebox",latex.options="{1}"}
Run `Intro2.R`, then enter the command `plot(fit)` in the console and follow the directions in the console. Figure out what just happened.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
By entering `?plot.lm` R brings up the Help page for the function `plot.lm` that carries out a `plot` command for an object produced by `lm`. This is one example of how R uses the fact that statistical analyses are stored as model objects. `fit` "knows" what kind of object it is (in this case an object of type `lm`, and so `plot(fit)` invokes a function that produces plots suitable for an `lm` object.
```
R produced a series of diagnostic plots exploring whether or not the fitted linear model is a suitable fit to the data. In each of the plots, the 3 most extreme points (the most likely candidates for "outliers") have been identified according to their sequence in the data set.
The axes in plots are scaled automatically, but the outcome is not always ideal (e.g. if you want several graphs with exactly the same axis limits). You can use the `xlim` and `ylim` arguments in `plot` to control the limits:
`plot(x,y,xlim=c(x1,x2), [other stuff])`
will draw the graph with the $x$-axis running from `x1` to `x2`, and using `ylim=c(y1,y2)` within the `plot` command will do the same for the $y$-axis.
```{block2, type="exercisebox",latex.options="{1}"}
Create a plot of growth rate versus light intensity with the $x$-axis running from 0 to 120 and the $y$-axis running from 1 to 4.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`plot(Light,rmax,xlim=c(0,120),ylim=c(1,4))`
```
You can place several graphs within a single figure by using the `par` function (short for "parameter") to adjust the layout of the plot. For example, the command
```{r,eval=FALSE}
par(mfrow=c(2,3))
```
divides the plotting area into 2 rows and 3 columns. As `R` draws a series of graphs, it places them along the top row from left to right, then along the next row, and so on. `mfcol=c(2,3)` has the same effect except that `R` draws successive graphs down the first column, then down the second column, and so on.
```{block2, type="exercisebox",latex.options="{1}",echo=T}
Modify the script as follows. Use `mfcol=c(2,1)` to create graphs of growth rate as a function of `Light`, and of `log(growth rate)` as a function of `log(Light)` in the same figure. Do the same again, using `mfcol=c(1,2)`.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`mfcol=c(2,1)`
`plot(rmax ~ Light)`
`plot(rmax ~ logLight)`
```
```{block2, type="exercisebox",latex.options="{1}"}
Use `?par` to read about other plot control parameters that you use `par` to set (you should definitely skim --- this is one of the longest help files in the whole R system!). Then draw a $2 \times 2$ set of plots, each showing the line $y=5x+3$ with $x$ running from 3 to 8, but with 4 different line styles and 4 different line colors.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`par(mfrow=c(2,2))`
`x = c(3:8)`
`y = 5*x+3`
`plot(y~x,type="l")`
`plot(y~x,type="l",lty=1,col="red")`
`plot(y~x,type="l",lty=2,col="blue")`
`plot(y~x,type="l",lty=4,col="orange")`
```
```{block2,type= "exercisebox",latex.options="{1}"}
Modify one of your scripts so that at the very end it saves the plot to disk. In Windows you can do this with specific functions like `jpeg` or `png`. Use `?jpeg` or `?png` to read about these functions. Note that the argument `filename` can include the path to a folder; for example, in Windows you can use `filename="c:/temp/Intro2Figure".`
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`png("test.png")`
`par(mfrow=c(2,2))`
`x = c(3:8)`
`y = 5*x+3`
`plot(y~x,type="l")`
`plot(y~x,type="l",lty=1,col="red")`
`plot(y~x,type="l",lty=2,col="blue")`
`plot(y~x,type="l",lty=4,col="orange")`
`dev.off()`
```
```{block2,type= "exercisebox",latex.options="{1}"}
Use google to see how to:
- rotate the y-axis labels
- change the background of the plot to grey
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
Google "rotate axis label plot r" and you will get a hit that shows you how to do it: i.e. set las=2
You can change the background color by setting par(bg="grey")
```
# Data types
`R` distinguishes a number of data types including vectors, matrices, data frames and lists that each have special properties and which are used for calculations and data storage.
## Vectors
An important class of data types are vectors and matrices (1- and 2-dimensional rectangular arrays of numbers). Operations with vectors and matrices may seem a bit abstract now, but we need them to do useful things later. The only properties of vectors are their type (or *class*) and length, although they can also have an associated list of names.
We've already seen two ways to create vectors in `R`:
1. A command in the console window or a script file listing the values,
such as
```{r}
initialsize=c(1,3,5,7,9,11)
```
2. Using `read.table`:
```{r,eval=FALSE}
initialsize=read.table("c:/temp/initialdata.txt")
```
(assuming of course that the file exists in the right place).
You can then use a vector in calculations as if it were a number (more or less)
```{r}
finalsize=initialsize+1
finalsize
newsize=sqrt(initialsize)
newsize
```
Notice that `R` applied each operation to every element in the vector. Similarly, commands like `initialsize-5, 2*initialsize, initialsize/10` apply subtraction, multiplication, and division to each element of the
vector. The same is true for
```{r}
initialsize^2
```
In `R` the default is to apply functions and operations to vectors in an *element by element* (or "vectorized") manner. This is an extremely useful propery in `R`.
### Functions for creating vectors
You can use the `seq` function to create a set of regularly spaced values. `seq`'s syntax is `x=seq(from,to,by)` or `x=seq(from,to)` or `x=seq(from,to,length.out)`.
The first form generates a vector starting with `from` with the last entry not extending further than than `to` in steps of `by`. In the second form the value of `by` is assumed to be 1 or -1, depending on
whether `from` or `to` is larger. The third form creates a vector with the desired endpoints and length. The syntax `from:to` is a shortcut for `seq(from,to)`:
```{r}
1:8
```
```{block2, type="exercisebox",latex.options="{1}"}
Use `seq` to create the vector `v=(1 5 9 13)`, and to create a vector going from 1 to 5 in increments of 0.2.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`seq(1,13,4)`
`seq(1,5,0.2)`
```
You can use `rep` to create a constant vector such as `(1 1 1 1)`; the basic syntax is `rep(values,lengths)`. For example,
```{r}
rep(3,5)
```
creates a vector in which the value 3 is repeated 5 times. `rep` will repeat a whole vector multiple times
```{r}
rep(1:3,3)
```
or will repeat each of the elements in a vector a given number of times:
```{r}
rep(1:3,each=3)
```
Even more flexibly, you can repeat each element in the vector a different number of times:
```{r, chunk_50}
rep( c(3,4),c(2,5) )
```
The value 3 was repeated 2 times, followed by the value 4 repeated 5 times.
`rep` can be a little bit mind-blowing as you get started, but it will turn out to be useful.
Table 3 lists some of the main functions for creating and working with vectors.
```{r, echo = FALSE, results = 'asis'}
data = rbind(c("\\texttt{seq(from,to,by=1)}" , " Vector of evenly spaced values, default increment = 1"),
c("\\texttt{seq(from, to, length.out)}" , " Vector of evenly spaced values, specified length"),
c("\\texttt{c(u,v,...)}" , " Combine a set of numbers and/or vectors into a single vector"),
c("\\texttt{rep(a,b)}" , " Create vector by repeating elements of \\texttt{a} by amounts in \\texttt{b}"),
c("\\texttt{as.vector(x)}" , " Convert an object of some other type to a vector" ),
c("\\texttt{hist(v)}" , " Histogram plot of value in v"),
c("\\texttt{mean(v),var(v),sd(v)}" , " Estimate of population mean, variance, standard deviation"),
c("","based on data values in \\texttt{v}"),
c("\\texttt{cor(v,w)}" , " Correlation between two vectors"))
kable(data, caption = "Some important `R` functions for creating and working with vectors. Many of these have other optional arguments; use the help system (e.g. \\texttt{?cor}) for more information. The statistical functions such as \\texttt{var} regard the values as samples from a population and compute an estimate of the population statistic; for example \\texttt{sd(1:3)=1}.", col.names = c("Function","Definition"), format="latex", booktabs=TRUE, escape = F) %>%
kable_styling(latex_options=c("scale_down"))
```
### Vector indexing
You will often want to extract a specific entry or other part of a vector. This procedure is called *vector indexing*, and uses square brackets (`[]`):
```{r}
z=c(1,3,5,7,9,11)
z[3]
```
`z[3]` extracts the third item, or *element*, in the vector `z`.
You can also access a block of elements using the functions for
vector construction, e.g.
```{r}
z[2:5]
```
extracts the second through fifth elements.
What happens if you enter `v=z[seq(1,5,2)]` ? Try it and see, and make sure you understand what happened.
You can extracted irregularly spaced elements of a vector. For example
```{r}
z[c(1,2,5)]
```
You can also use indexing to **set specific values within a vector**. For
example,
```{r}
z[1]=12
```
changes the value of the first entry in `z` while leaving all the rest alone, and
```{r}
z[c(1,3,5)]=c(22,33,44)
```
changes the first, third, and fifth values (note that we had to use `c` to create the vector --- can you interpret the error message you get if you
try `z[1,3,5]` ?)
```{block2, type="exercisebox",latex.options="{1}"}
Write a *one-line* command to extract a vector consisting of the second, first, and third elements of `z` *in that order*.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`z=c(1,3,5,7,9,11)`
`z[c(2,1,3)]`
```
```{block2, type="exercisebox",latex.options="{1}"}
Write a script file that computes values of
$y=\frac{(x-1)}{(x+1)}$ for $x=1,2,\cdots,10$, and plots $y$ versus $x$
with the points plotted and connected by a line
*hint:* in `?plot`, search for `type`).
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`x = c(1:10)`
`y = (x-1)/(x+1)`
`plot(y~x,type="b")`
```
The sum of the geometric series $1 + r + r^2 + r^3 + ... + r^n$ approaches the limit $1/(1-r)$ for $r < 1$ as $n \rightarrow \infty$.
```{block2, type="exercisebox",latex.options="{1}"}
Set the values $r=0.5$ and $n=10$, and then write a *one-line* command that creates the vector $G = (r^0,r^1,r^2,...,r^n)$. Compare the sum (using `sum`) of this vector to the limiting value $1/(1-r)$.
Repeat for $n=50$. (*Note* that comparing very similar numeric values can be tricky: rounding can happen, and some numbers cannot be represented exactly in binary (computer) notation. By default `R` displays 7~significant digits (`options("digits")`).
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`r = 0.5`
`n =10`
`sum(r^c(1:n))`
`n =50`
`sum(r^c(1:n))`
```
For example:
```{r}
x = 1.999999
x
x-2
x=1.9999999999999
x
x-2
```
All the digits are still there, in the second case, but they are not shown.
Also note that `x-2` is not exactly $-1 \times 10^{-13}$; this is unavoidable.)
### Logical operators
Logical operators return a value of `TRUE` or `FALSE`. For example,
try:
```{r}
a=1
b=3
d=a<b
e=(a>b)
d
e
```
The parentheses around (`a>b`) are optional but make the code easier to read.
One special case where you *do* need parentheses (or spaces) is when you make comparisons with negative values; `a<-1` will surprise you by setting `a=1`,
because `<-` (representing a left-pointing arrow) is equivalent to `=` in `R`. Use `a< -1`, or more safely `a<(-1)`, to make this comparison.
```{r, echo = FALSE, results = 'asis'}
data = rbind(c("\\texttt{x<y}","less than"),
c("\\texttt{x>y}","greater than"),
c("\\texttt{x<=y}","less than or equal to"),
c("\\texttt{x>=y}","greater than or equal to"),
c("\\texttt{x==y}","equal to"),
c("\\texttt{x!=y}","\\emph{not} equal to"))
kable(data, caption = "Some comparison operators in `R`. Use \\texttt{?Comparison} to learn more.", col.names = c("Operator","Definition"), format="latex", booktabs=TRUE, escape = F)
```
When we compare two vectors or matrices of the same size, or compare a
number with a vector or matrix, comparisons are done element-by-element.
For example,
```{r}
x=1:5
b=(x<=3)
```
So if `x` and `y` are vectors, then `(x==y)` will return a vector of values giving the element-by-element comparisons. If you want to know whether `x` and `y` are identical vectors, use `identical(x,y)` which returns a single value: `TRUE` if each entry in `x` equals the corresponding entry in `y`, otherwise `FALSE`. You can use `?Logical` to read more about logical operators. Note the difference between = and ==
```{block2, type="exercisebox",latex.options="{1}"}
Can you figure out what happened in the following cautionary tale below?
```
```{r}
a = 1:3
b = 2:4
a==b
a=b
a==b
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
You overwrote a by b in the command `a=b` and so the last statement confirms that they are identical
```
Exclamation points `!` are used in `R` to mean "not"; `!=` (not `==`) means "not equal to".
`R` also does arithmetic on logical values, treating `TRUE` as 1 and `FALSE` as 0. So `sum(b)` returns the value 3, telling us that three entries of `x` satisfied the condition (`x<=3`). This is useful for (e.g.) seeing how many of the elements of a vector are larger than a cutoff value. Build more complicated conditions by using *logical operators* to combine comparisons:
* `!`: Negation
* `&`, `&&`: AND
* `|`, `||`: OR
OR is *non-exclusive*, meaning that `x|y` is true if either `x` or `y` *or both* are true (a ham-and-cheese sandwich would satisfy the condition "ham OR cheese"). For example, try
```{r}
a=c(1,2,3,4)
b=c(1,1,5,5)
(a<b)& (a>3)
(a<b) | (a>3)
```
and make sure you understand what happened. If it's confusing, try breaking up the expression
and looking at the results of `a<b` and `a>3` separately first. The two forms of AND and OR differ in how they handle vectors. The shorter one does element-by-element comparisons; the longer one only looks at the
first element in each vector.
We can also use *logical* vectors (lists of `TRUE` and `FALSE` values) to pick elements out of vectors.
This is important, e.g., for subsetting data (getting rid of those pesky outliers!)
As a simple example, we might want to focus on just the low-light values of $r_{max}$ in the *Chlorella* example:
```{r}
X=read.table("ChlorellaGrowth.txt",header=TRUE)
Light=X[,1]
rmax=X[,2]
lowLight = Light[Light<50]
lowLightrmax = rmax[Light<50]
lowLight
lowLightrmax
```
What is really happening here (think about it for a minute) is that `Light<50` generates a logical vector the same length as `Light` (`TRUE TRUE TRUE ...`) which is then used to select the appropriate
values.
If you want the positions at which `Light` is lower than 50, you could say
`(1:length(Light))[Light<50]`, but you can also use a built-in function: `which(Light<50)`. If you wanted the position at which the maximum value
of `Light` occurs, you could say `which(Light==max(Light))`. (This normally results in a vector of length 1; when could it give a longer vector?) There is even a built-in command for this specific function, `which.max` (although `which.max` always returns just the *first* position at which the maximum occurs).
```{block2, type="exercisebox",latex.options="{1}"}
What would happen if instead of setting `lowLight` you replaced `Light` by saying `Light=Light[Light<50]`, and then `rmax=rmax[Light<50]`?
Why would that be wrong?
Try it with some temporary variables --- set `Light2=Light` and `rmax2=rmax` and then play with `Light2` and `rmax2` so you dont mess up your working variables --- and work out what happened ...
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`Light[Light<50 & rmax <= 2.0]`
`rmax[Light<50 & rmax <= 2.0]`
```
We can also combine logical operators (making sure to use the element-by-element `&` and `|` versions of AND and OR):
```{r}
Light[Light<50 & rmax <= 2.0]
rmax[Light<50 & rmax <= 2.0]
```
```{block2, type="exercisebox",latex.options="{1}"}
`runif(n)` is a function (more on it soon) that generates a vector of `n` random, uniformly distributed
numbers between 0 and 1. Create a vector of 20 numbers, then select the subset of those numbers that
is less than the mean. (If you want your answers to match mine exactly, use `set.seed(273)` to set the random-number generator to a particular starting point before you use `runif`. [273 is an arbitrary number I chose].)
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`a = runif(20)`
`a[a < mean(a)]`
```
```{block2, type="exercisebox",latex.options="{1}"}
Find the *positions* of the elements that are less than the mean of the vector you just created (e.g. if your vector were `(0.1 0.9. 0.7 0.3)` the answer would be `(1 4)`).
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`which(a < mean(a))`
```
As I mentioned in passing above, vectors can have names associated with their elements: if they do, you can also extract elements by name (use `names` to find out the names).
```{r}
x = c(first=7,second=5,third=2)
names(x)
x["first"]
x[c("third","first")]
```
Finally, it is sometimes handy to be able to drop a particular set of elements, rather than taking a particular set: you can do this with negative indices. For example, `x[-1]` extracts all but the first
element of a vector.
```{block2, type="exercisebox",latex.options="{1}"}
Specify two ways to take only the elements in the odd positions (first, third, ...) of a vector of arbitrary length.
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`n = 20`
`a = c(1:n)`
`a1 = a[seq(1,n,2)]`
`a2 = a[-seq(2,n,2)]`
```
## Matrices
### Creating matrices
A matrix is a two-dimensional array, and has the same kind of variables in every column. You can create matrices of numbers by creating a vector of the matrix entries, and then reshaping them to the desired number of rows and columns using the function `matrix`. For example
```{r}
(X=matrix(1:6,nrow=2,ncol=3))
```
takes the values 1 to 6 and reshapes them into a 2 by 3 matrix.
By default `R` loads the values into the matrix *column-wise* (this is probably counter-intuitive since we're used to reading tables row-wise). Use the optional parameter `byrow` to change this behavior.
For example :
```{r}
(A=matrix(1:9,nrow=3,ncol=3,byrow=TRUE))
```
`R` will re-cycle through entries in the data vector, if necessary to fill a matrix of the specified size. So for example
```{r,eval=FALSE}
matrix(1,nrow=10,ncol=10)
```
creates a $10 \times 10$ matrix of ones.
```{block2, type="exercisebox",latex.options="{1}"}
Use a command of the form `X=matrix(v,nrow=2,ncol=4)` where `v` is a data vector, to create the following matrix `X`:
```
```{block2, type= "solutionbox", latex.options="{1}",echo=T}
`matrix(rep(1:2,4),nrow=2)`
```
```{r, echo = FALSE}
matrix(rep(1:2,4),nrow=2)
```
If you can, try to use `R` commands to construct the vector rather than typing out all of the individual values.