-
Notifications
You must be signed in to change notification settings - Fork 13
/
all_code.Rmd
2283 lines (1766 loc) · 60 KB
/
all_code.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: "Intro2R"
author: "Jonathan Rosenblatt"
date: "March 18, 2015"
output: html_document
---
# R Basics
Tips for this introction:
- If you are working alone, consider starting with "An Introduction to R" here:
http://cran.r-project.org/manuals.html
- Make sure you use RStudio.
- ctrl+return to run lines from editor.
- alt+shift+k for RStudio keyboard shortcuts.
- ctrl+alt+j to navigate between sections
- tab for autocompletion
- ctrl+1 to skip to editor.
- ctrl+2 to skip to console.
- ctrl+8 to skip to the environment list.
- Folding:
- alt+l collapse chunk.
- alt+shift+l unfold chunk.
- alt+o collapse all.
- alt+shift+o unfold all.
## Simple calculator
```{r example}
10+5
70*81
2**4
2^4
log(10)
log(16, 2)
log(1000, 10)
```
## Controlling output format:
```{r}
round(log(10)) # typically most useful
signif(log(10))
prettyNum(log(10), digits=5)
format(log(10), digits=4, scientific=T, justify='right')
```
## Probability calculator
Wish you knew this when you did Intro To Probability class?
```{r}
dbinom(x=3, size=10, prob=0.5) # For X~B(n=10, p=0.5) returns P(X=3)
dbinom(3, 10, 0.5)
pbinom(q=3, size=10, prob=0.5) # For X~B(n=10, p=0.5) returns P(X<=3)
dbinom(x=0, size=10, prob=0.5)+dbinom(x=1, size=10, prob=0.5)+dbinom(x=2, size=10, prob=0.5)+dbinom(x=3, size=10, prob=0.5) # Same as previous
qbinom(p=0.1718, size=10, prob=0.5) # For X~B(n=10, p=0.5) returns k such that P(X<=k)=0.1718
rbinom(n=1, size=10, prob=0.5)
rbinom(n=10, size=10, prob=0.5)
rbinom(n=100, size=10, prob=0.5)
```
## Getting help
Get help for a particular function.
```{r, eval=FALSE}
?dbinom
help(dbinom)
```
Search local help files for a particular string.
```{r, eval=FALSE}
??binomial
help.search('dbinom')
```
Load a menu with several important manuals:
```{r, eval=FALSE}
help.start()
```
## Variable asignment:
Asignments into a variable named "x":
```{r}
x = rbinom(n=1000, size=10, prob=0.5) # Works. Bad style.
x <- rbinom(n=1000, size=10, prob=0.5) # Asignments into a variable named "x"
```
More on style: http://adv-r.had.co.nz/Style.html
Print contents:
```{r}
x
print(x)
(x <- rbinom(n=1000, size=10, prob=0.5)) # Assign and print.
```
Operate on the object
```{r}
mean(x)
var(x)
hist(x)
rm(x) # remove variable
```
For more information on distributions see http://cran.r-project.org/web/views/Distributions.html
## Piping for better style and readability
```{r}
# install.packages('magrittr')
library(magrittr)
```
```{r}
x <- rbinom(n=1000, size=10, prob=0.5)
x %>% var() # Instead of var(x)
x %>% hist() # Instead of hist(x)
x %>% mean() %>% round(2) %>% add(10)
```
This example clearly demonstrates the benefits (from http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html)
```{r}
# Functional (onion) style
car_data <-
transform(aggregate(. ~ cyl,
data = subset(mtcars, hp > 100),
FUN = function(x) round(mean(x, 2))),
kpl = mpg*0.4251)
# magrittr style
car_data <-
mtcars %>%
subset(hp > 100) %>%
aggregate(. ~ cyl, data = ., FUN = . %>% mean %>% round(2)) %>%
transform(kpl = mpg %>% multiply_by(0.4251)) %>%
print
```
## Vector creation and manipulation
```{r}
c(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)
10:21
seq(from=10, to=21, by=1)
x seq(from=10, to=21, by=2)
x <- c(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)
x
```
You can assign AFTER the computation is finished:
```{r}
c(1,2,3)
y<- .Last.value
y
```
Operations usually work element-wise:
```{r}
x+2
x*2
x^2
sqrt(x)
log(x)
```
## Simple plotting
```{r}
x<- 1:100; y<- 3+sin(x) # Create arbitrary data
plot(x = x, y = y) # x,y syntax
plot(y ~ x) # y~x syntax (I like better)
```
Control plot appearance:
```{r}
plot(y~x, type='l', main='Plotting a connected line')
plot(y~x, type='h', main='Sticks plot', xlab='Insert x axis label', ylab='Insert y axis label')
plot(y~x, pch=5)
plot(y~x, pch=10, type='p', col='blue', cex=4)
abline(3, 0.002)
```
Available plotting options
```{r, eval=FALSE}
example(plot)
example(points)
?plot
help(package='graphics')
```
When your plotting gets serious, move to ggplot2 and ggvis as soon as possible.
___
## Data frame Manipulation
data.frames extend the matrix class, in that they allow the binding of vectors of several classes (with same length).
```{r}
x<- 1:100; y<- 3 + sin(x)
class(x) # R (high) level representation of an object.
# mode(x)
# typeof(x)
```
Create and checkout your first data frame
```{r}
frame1 <- data.frame(x=x, sin=y)
frame1
head(frame1)
frame1 %>% head() # just print the beginning
frame1 %>% View() # Excel-like view (never edit!)
class(frame1) # the object is of type data.frame
dim(frame1)
dim(x)
length(frame1)
length(x)
str(frame1) # the inner structure of an object
attributes(frame1) # get the objec's meta data
```
### Exctraction
single element:
```{r}
frame1[1, 2]
frame1[2, 1]
```
Exctract _column_ by index:
```{r}
frame1[1, ]
frame1[,1] %>% t
frame1[,1] %>% t %>% dim
```
Exctract column by name:
```{r}
names(frame1)
frame1[, 'sin']
dim(frame1[, 'sin']) # extract as a vector. no dim attribute.
frame1['sin']
dim(frame1['x',]) # extract as a data.frame. has dim attribute.
frame1[,1:2] %>% class
frame1[2] %>% class
frame1[2, ] # extract a row
frame1$sin %>% class
```
`subset()` does the same
```{r}
subset(frame1, select=sin)
subset(frame1, select=2)
subset(frame1, select= c(2,0))
```
Sanity conservation notice!
Always think if you want to extract a vector or a frame:
- Note the difference between `[]` and `[[]]` exctraction!
- Note the difference between `frame[,1]` and `frame[1]`.
```{r}
a <- frame1[1]
b <- frame1[[1]]
a==b # Seems identical. But not really:
class(a)
class(b)
# Causes different behaviour:
a[1]
b[1]
```
More about extraction: http://adv-r.had.co.nz/Subsetting.html
### dplyr package
`dplyr` makes the manupilation of data.frames a breeze.
It is very fast, and straightforward
Install the package:
```{r}
# install.packages('dplyr')
```
The following examples are taken from:
https://github.com/justmarkham/dplyr-tutorial/blob/master/dplyr-tutorial.Rmd
```{r}
# install.packages('nycflights13')
library(nycflights13)
dim(flights)
View(flights)
names(flights)
class(flights) # a tbl_df is an extension of the data.frame class
library(dplyr) # calling dplyr
filter(flights, month == 1, day == 1) #dplyr style
flights[flights$month == 1 & flights$day == 1, ] # old style
flights %>% filter(month == 1, day == 1) # dplyr with magrittr style (yes!)
filter(flights, month == 1 | month == 2)
sli1ce(flights, 1:10) # selects rows
arrange(flights, year, month, day) # sort
arrange(flights, desc(arr_delay)) # sort descending
select(flights, year, month, day) # select columns
select(flights, year:day) # select column range
select(flights, -(year:day)) # drop columns
rename(flights, tail_num = tailnum) # rename variables
# add a new computed colume
mutate(flights,
gain = arr_delay - dep_delay,
speed = distance / air_time * 60)
# you can refer to columns just created!
mutate(flights,
gain = arr_delay - dep_delay,
gain_per_hour = gain / (air_time / 60)
)
# keep only new variables
transmute(flights,
gain = arr_delay - dep_delay,
gain_per_hour = gain / (air_time / 60)
)
# simple statistics
summarise(flights,
delay = mean(dep_delay, na.rm = TRUE)
)
sample_n(flights, 10) # random subsample
sample_frac(flights, 0.01) # random subsample
```
Subgroup operations
```{r}
by_tailnum <- group_by(flights, tailnum)
by_tailnum %>% class # a groupping object
delay <- summarise(by_tailnum,
count = n(),
avg.dist = mean(distance, na.rm = TRUE),
avg.delay = mean(arr_delay, na.rm = TRUE))
delay <- filter(delay, count > 20, avg.dist < 2000)
View(delay)
destinations <- group_by(flights, dest)
summarise(destinations,
planes = n_distinct(tailnum),
flights = n()
)
# Grouping works in a hirarchy. summarise() peels outer layer.
daily <- group_by(flights, year, month, day)
(per_day <- summarise(daily, flights = n()))
(per_month <- summarise(per_day, flights = sum(flights)))
(per_year <- summarise(per_month, flights = sum(flights)))
```
Two table operations
```{r}
airlines %>% View
flights2 <- flights %>% select(year:day, hour, origin, dest, tailnum, carrier)
flights2 %>% left_join(airlines) # join on left table with automatic matching.
flights2 %>% left_join(weather)
flights2 %>% left_join(planes, by = "tailnum") # with named matching
flights2 %>% left_join(airports, c("dest" = "faa"))
flights2 %>% left_join(airports, c("origin" = "faa"))
```
Types of join
```{r}
(df1 <- data_frame(x = c(1, 2), y = 2:1))
(df2 <- data_frame(x = c(1, 3), a = 10, b = "a"))
df1 %>% inner_join(df2) # SELECT * FROM x JOIN y ON x.a = y.a
df1 %>% left_join(df2) # SELECT * FROM x LEFT JOIN y ON x.a = y.a
df1 %>% right_join(df2) # SELECT * FROM x RIGHT JOIN y ON x.a = y.a
df2 %>% left_join(df1)
df1 %>% full_join(df2) # SELECT * FROM x FULL JOIN y ON x.a = y.a
# return only unmatched cases
flights %>%
anti_join(planes, by = "tailnum") %>%
count(tailnum, sort = TRUE)
# SELECT * FROM x WHERE NOT EXISTS (SELECT 1 FROM y WHERE x.a = y.a)
df1 %>% semi_join(df2, by = "x") # SELECT * FROM x WHERE EXISTS (SELECT 1 FROM y WHERE x.a = y.a)
```
Set operations
```{r}
(df1 <- data_frame(x = 1:2, y = c(1L, 1L)))
(df2 <- data_frame(x = 1:2, y = 1:2))
intersect(df1, df2) # SELECT * FROM x INTERSECT SELECT * FROM y
union(df1, df2) # SELECT * FROM x UNION SELECT * FROM y
setdiff(df1, df2) # SELECT * FROM x EXCEPT SELECT * FROM y
setdiff(df2, df1)
```
Leaving dplyr for now...
### Arrays
Arrays generalize matrices to higher dimension:
```{r}
x<- array(1:24, dim=c(6,4) )
x[6,4]
x<- array(1:24, dim=c(6,2,2) )
x[6,2,2]
x<- array(1:24, dim=c(2,3,2,2) )
x[2,3,2,2]
```
## Data Import and export
For a complete review see:
http://cran.r-project.org/doc/manuals/R-data.html
also in help.start() -> "Import and Export Manual"
### Import from WEB
`read.table()` is the main importing workhorse.
```{r}
URL <- 'http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/bone.data'
tirgul1 <- read.table(URL)
```
Always look at the imported result!
```{r}
View(tirgul1)
# hmmm... header interpreted as data. Fix with header=TRUE:
tirgul1 <- read.table(URL, header = TRUE)
View(tirgul1)
```
### Import .csv files
Let's write a simple file so that we have something to import:
```{r}
View(airquality) # examine the data to export
(temp.file.name <- tempfile()) # get an arbitrary file name
write.csv(x = airquality, file = temp.file.name) #export
```
Now let's import:
```{r}
# my.data<- read.csv(file='/home/jonathan/Projects/...')
my.data<- read.csv(file=temp.file.name)
View(my.data)
```
__Note__: Under MS Windows(R) you might want need '\\\' instead of '/'
### Imprt .txt files
Tries to guess the seperator
```{r, eval=FALSE}
my.data<- read.table(file='C:\\Documents and Settings\\Jonathan\\My Documents\\...') #
```
Specifies the seperator explicitly
```{r, eval=FALSE}
my.data<- read.delim(file='C:\\Documents and Settings\\Jonathan\\My Documents\\...')
```
If you care about your sanity, see ?read.table before starting imports.
### Writing Data to files
Get and set the current directory:
```{r, eval=FALSE}
getwd() #What is the working directory?
setwd() #Setting the working directory in Linux
```
```{r}
write.csv(x=tirgul1, file='/tmp/tirgul1.csv') #
```
See ?write.table for details.
### .XLS files
Strongly recommended to convert to .csv
If you still insist see:
http://cran.r-project.org/doc/manuals/R-data.html#Reading-Excel-spreadsheets
### Massive files
Better store as matrices and not data.frames.
`scan()` is faster than `read.table()` but less convenient:
Create the example data:
```{r}
cols<- 1e3
# Note: On Windoes you might neet to change /tmp/A.txt to /temp/A.txt
rnorm(cols^2) %>%
matrix(ncol=cols) %>%
write.table(file='/tmp/A.txt', col.names= F, row.names= F)
# Measure speed of import:
system.time(A<- read.table('/tmp/A.txt', header=F))
system.time(A <- scan(file='/tmp/A.txt', n = cols^2) %>%
matrix(ncol=cols, byrow = TRUE))
file.remove('/tmp/A.txt')
```
This matter will be revisited in the last class.
### Databases:
Start [here](https://rforanalytics.wordpress.com/useful-links-for-r/odbc-databases-for-r/)
### Hands on example (from the WEB)
```{r}
URL <- 'http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/bone.data'
tirgul1 <- read.table(URL, header = TRUE)
names(tirgul1)
tirgul1 %>% head
tirgul1 %>% tail
View(tirgul1)
dim(tirgul1)
length(tirgul1)
```
R can be object oriented (read about S3 and S4 if interested).
See how `summary()` behaves differely on different object classes:
```{r}
class(tirgul1[, 1]); class(tirgul1[, 2]); class(tirgul1[, 3]); class(tirgul1[, 4])
summary(tirgul1)
```
Matrix is more efficient than data frames. But can store only a single class of vectors.
```{r}
tirgul.matrix <- as.matrix(tirgul1)
tirgul.matrix
class(tirgul.matrix)
# notice everything has been cast to the most general class.
class(tirgul.matrix[, 1]); class(tirgul.matrix[, 2]); class(tirgul.matrix[, 3]); class(tirgul.matrix[, 4])
summary(tirgul.matrix)
```
Note: if re-writing an expression bothers you (as it should!), here are some solutions:
```{r}
# The apply family of functions:
sapply(tirgul.matrix, class)
# looping
for(j in 1:ncol(tirgul.matrix)) print(class(tirgul.matrix[,j]))
```
Make sure you read `?sapply`.
LISP fans might also like to read `?MAP`.
Operations _within_ data objects:
```{r}
plot(tirgul1$gender)
tirgul1$gender %>% plot() #
with(tirgul1, plot(gender) ) # Same opration. Different syntax.
mean(tirgul1$age)
tirgul1$age %>% mean() #
with(tirgul1, mean(age) ) # Same opration. Different syntax.
```
```{r}
tirgul1$age <- tirgul1$age * 365
tirgul1<- transform(tirgul1, age=age*365 ) #Age in days
with(tirgul1, mean(age) )
tirgul1<- transform(tirgul1, age=age/365 ) #Does this revert back to years?
with(tirgul1, mean(age) )
```
Then again, many of these fnuctions are replaced by more friendly functions in the dplyr package (see below).
## Sorting
```{r}
(x<- c(20, 11, 13, 23, 7, 4))
(y<- sort(x))
(ord<- order(x))
x[ord] # Exctracting along the order is the same as sorting.
ranks<- rank(x)
identical(y[ranks] , x) # Compares two objects
(z<- c('b','a','c','d','e','z'))
xz<- data.frame(x,z)
sort(xz)
xz[ord,] # Sorting a data frame using one column
```
## Looping
For a crash course in R programming (not only data analysis) try:
http://adv-r.had.co.nz/
The usual for(), while(), repeat()
```{r}
for (i in 1:100){
print(i)
}
```
```{r}
for (helloeveryone in seq(10, 100, by=2) ){
print(helloeveryone)
}
```
## Recursion
Typically very slow due to memory management issues.
```{r}
fib<-function(n) {
if (n < 2) fn<-1
else fn<-Recall(n - 1) + Recall(n - 2)
return(fn)
}
fib(30)
```
## Finding your objects
```{r}
ls() #Lists all available objects
ls(pattern='x')
ls(pattern='[0-9]') # Search using regular expressions
ls(pattern='[A-Z]')
```
ctrl+8 in RStudio.
### What are the available environments?
```{r}
search() # This is the search hirarchy of called objects.
```
When you start serious programming in R, read this:
http://adv-r.had.co.nz/Environments.html
# Univariate Exploratory Statistics
## Exploring Categorical Variables
```{r}
gender <- c(rep('Boy', 10), rep('Girl', 12))
drink <- c(rep('Coke', 5), rep('Sprite', 3), rep('Coffee', 6), rep('Tea', 7), rep('Water', 1))
class(gender);class(drink)
cbind(gender, drink)
table1 <- table(gender, drink)
table1
```
Margins
```{r}
table(gender)
table(drink)
dotchart(as.matrix(table(gender)))
dotchart(as.matrix(table(drink)))
barplot(table1, legend.text=T)
barplot(t(table1), legend.text=T)
plot(table1, main="Frequency Bar Chart", sub="Notice columns width is also propostional to counts!")
plot(t(table1))
data1<-data.frame(gender, drink)
plot(data1)
plot(gender~drink) #Will not work
plot(gender, drink) #Will not work
gender.n<-apply(table1, 1, sum)
gender.n
drink.n<-apply(table1, 2, sum)
drink.n
apply(table1, 2, '/', gender.n)
apply(table1, 1, '/', drink.n)
apropos('table')
margin.table(table1, 2)
prop.table(table1, 1)
prop.table(table1, 2)
par(mfrow=c(1, 2))
pie(prop.table(table1, 1)['Boy', ], main='Drinks given Boys')
pie(prop.table(table1, 1)['Girl', ], main='Drinks given Girls')
barplot(prop.table(table1, 1)['Boy', ], main='Boys');barplot(prop.table(table1, 1)['Girl', ], main='Girls')
par(mfrow=c(2, 3))
pie(prop.table(table1, 1)[, 'Coffee'], main='Coffee');pie(prop.table(table1, 1)[, 'Coke'], main='Coke');
pie(prop.table(table1, 1)[, 'Sprite'], main='Sprite');pie(prop.table(table1, 1)[, 'Tea'], main='Tea');
pie(prop.table(table1, 1)[, 'Water'], main='Water');
par(mfrow=c(1, 1))
barplot(table1)
barplot(prop.table(table1, 1))
barplot(prop.table(table1, 2))
barplot(t(prop.table(table1, 1)), legend.text=T)
```
Using the ggplot2 package
```{r}
library(ggplot2)
qplot(gender, data=data1, geom='bar', fill=drink )
qplot(gender, data=data1, geom='bar' ) + facet_grid(~drink)
qplot(drink, data=data1, geom='bar' ) + facet_grid(~gender)
gender<-factor(gender);drink=factor(drink)
```
## Exploring Continous Variables
Manual Histogram
```{r}
x <- c(-2.44, -1.70, -1.45, -1.27, -1.25, -1.12, -1.10, -1.05, -1.01, -0.50, -0.33, -0.12, -0.01, 0.24, 0.51, 0.80, 1.04, 1.15, 1.28, 1.77)
stripchart(x)
x<- c(rnorm(500),rnorm(300,3))
stripchart(x)
hist(x, prob=T,main='') ## Disjoint window histogram
rug(x)
lines(density(x, kernel='rectangular', bw=0.1), main='') ## Simple moving average with width 1
title(expression(W(t)==ifelse(abs(t)<=0.5, 1, 0)))
```
Generating and exploring normal data
```{r}
sample1<-rnorm(100)
table(sample1)
barplot(table(sample1))
stem(sample1)
stem(sample1, scale=2)
stem(sample1, scale=0.5)
hist(sample1, freq=T, main='Counts')
hist(sample1, freq=F, main='Frequencies')
lines(density(sample1))
rug(sample1)
```
## The Boxplot
```{r}
boxplot(sample1)
text(x=1.3, y=c(-0.6195636, 0.2581893, 0.7848411), labels=c('Quartile 1', 'Median', 'Quartile 3'))
abline(h=qnorm(0.25), col='red')
abline(h=qnorm(0.5), col='blue')
abline(h=qnorm(0.75), col='red')
# Adjusting the Boxplot fences for the size of the data:
giantSample<- rnorm(100000)
par(mfrow=c(2,2))
boxplot(giantSample, range=1) # Too many outliers :-(
boxplot(giantSample, range=2)
boxplot(giantSample, range=3) # Too few outliers :-(
boxplot(giantSample, range=2.5) # Good distance of fences :-)
par(mfrow=c(1,1))
```
Several different visualisations:
```{r}
sample2<-rnorm(1000)
stem(sample2)
hist(sample2)
plot(density(sample2))
rug(sample2)
```
True data
```{r}
URL <- 'http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/bone.data'
bone <- read.table(URL, header = TRUE)
names(bone)
summary(bone)
stripchart(bone['age'])
stem(bone[, 'age'])
hist(bone[, 'age'], prob=T)
lines(density(bone[, 'age']))
with(bone, rug(age))
ind<-bone[, 'gender']=='male'
par(mfrow=c(2, 1))
plot(density(bone[ind, 'age']), main='Male')
rug(bone[ind,'age'])
plot(density(bone[!ind, 'age']), main='Female')
rug(bone[!ind,'age'])
plot(density(bone[ind, 'age']), main='Male', xlim=c(5, 30)) # Adjusting x axis to fit both genders
plot(density(bone[!ind, 'age']), main='Female', xlim=c(5, 30)) # Adjusting x axis to fit both genders
boxplot(bone[ind, 'age'], main='Male')
boxplot(bone[!ind, 'age'], main='Female')
par(mfrow=c(1, 1))
boxplot(bone$age~bone$gender)
with(bone, boxplot(spnbmd~gender))
```
## Graphical parameters
```{r}
attach(bone)
stripchart(age)
stripchart(age~gender)
stripchart(age~gender, v=T)
boxplot(age~gender)
boxplot(age~gender, horizontal=T, col=c('pink','lightblue') )
title(main='Amazing Boxplots!')
title(sub="Well actually.. I've seen better Boxplots")
plot(density(age),main='')
plot(density(age),main='',type='h')
plot(density(age),main='',type='o')
plot(density(age),main='',type='p')
plot(density(age),main='',type='l')
?plot.default
plot(density(age),main='')
rug(age)
boxplot(age, add=T, horizontal=T, at=0.02, boxwex=0.05, col='grey')
title(expression(alpha==f[i] (beta)))
example(plotmath)
par(mfrow=c(2,1))
(males<- gender=='male')
plot(density(age[males]), main='Male') ; rug(age[males])
plot(density(age[!males]), main='Female') ; rug(age[!males])
range(age)
plot(density(age[males]), main='Male', xlim=c(9,26)) ; rug(age[males])
plot(density(age[!males]), main='Female', xlim=c(9,26)) ; rug(age[!males])
par(mfrow=c(1,2))
plot(density(age[males]), main='Male', xlim=c(9,26)) ; rug(age[males])
plot(density(age[!males]), main='Female', xlim=c(9,26)) ; rug(age[!males])
par(mfrow=c(1,1),ask=T)
plot(density(age[males]), main='Male', xlim=c(9,26)) ; rug(age[males])
plot(density(age[!males]), main='Female', xlim=c(9,26)) ; rug(age[!males])
plot(density(age[males]), main='Male', xlim=c(9,26),ylim=c(0,0.08))
par(mfrow=c(1,1),ask=F, new=T)
plot(density(age[!males]), main='Female', xlim=c(9,26),ylim=c(0,0.08))
plot(density(age[males]), main='Male', xlim=c(9,26))
lines(density(age[!males]), main='Female', xlim=c(9,26))
plot(density(age[males]), main='Male', xlim=c(9,26))
lines(density(age[!males]), main='Female', xlim=c(9,26),lwd=2)
plot(density(age[males]), xlim=c(9,26), main='')
lines(density(age[!males]), xlim=c(9,26),lty=2)
legend(locator(1), legend=c("Male","Female"), lty=c(1,2))
plot(density(age[males]), xlim=c(9,26), main='',col='blue', lwd=2)
lines(density(age[!males]), xlim=c(9,26),lty=2, col='red',lwd=2)
legend(locator(1), legend=c("Male","Female"), lty=c(1,2), col=c('blue','red'))
plot(density(age[males]), main='Male', xlim=c(9,26))
points(density(age[!males]), main='Female', xlim=c(9,26), bg='red')
points(locator(3),pch="+")
points(locator(3),pch=10, cex=4)
plot(density(age[males]), main='Male', xlim=c(9,26))
points(density(age[!males]), main='Female', xlim=c(9,26), bg='red')
points(locator(6),pch=c('a','b','c'))
```
## Integer data
Integer data will most certainly produce overlaps if plotted. Either add jitter, or treat as discrete.
```{r}
r.age<-round(age)
plot(density(r.age))
rug(r.age)
plot(density(r.age, from=9))
rug(jitter(r.age))
hist(r.age)
rug(jitter(r.age))
```
## Plotting
### Preparing data for plotting
2D data can be in either `wide' or `long' format.
Most R functions are designed for long formats.
Let's start by trying to plot in the wide format.
Notice each dosage is plotted seperately (yes, I could have looped).
```{r}
wide.data<-data.frame(id=1:4, age=c(40,50,60,50), dose1=c(1,2,1,2),dose2=c(2,1,2,1), dose4=c(3,3,3,3))
wide.data
plot(dose1~age, data=wide.data, ylim=range(c(dose1,dose2,dose4)), ylab='')
points(dose2~age, data=wide.data, pch=2)
points(dose4~age, data=wide.data, pch=3)
```
Ploting in long format is much easier.
I will first convert the data manually.
```{r}
(dose.type<-c(
rep('dose1', length(wide.data$dose1)),
rep('dose2', length(wide.data$dose2)),
rep('dose4', length(wide.data$dose4))))
(dose<- c(wide.data$dose1,wide.data$dose2,wide.data$dose4))
(long.id<- rep(wide.data$id,3))
(long.age<- rep(wide.data$age,3))
long.data <- data.frame(long.id, long.age, dose.type, dose)
View(long.data)
plot(dose~long.age, data=long.data, pch=as.numeric(dose.type))
```
I will now try to avoid this manual reshaping.
### Reshaping data
#### base package
```{r}
stack(data.frame(wide.data$dose1,wide.data$dose2,wide.data$dose4))
reshape(wide.data, varying=list(c("dose1","dose2","dose4")), direction="long", idvar=c("id","age"), v.names="dose")
reshape(wide.data, varying=list(c("dose1","dose2","dose4")), direction="long", idvar="id", timevar="age", v.names="dose")
```
#### respahe package
```{r}
# melt() is much more confortable then reshape( )
library(reshape)
melted.data<- melt(data=wide.data, id.vars=c("id","age") )
cast(melted.data, age+id~variable)
cast(melted.data)
```
#### tidyr package
This is the package I recommend if you cannot reshape manually.
Example from [here](http://blog.rstudio.org/2014/07/22/introducing-tidyr/)
```{r}
library(tidyr)
library(dplyr)
# Data in wide format:
messy <- data.frame(
name = c("Wilbur", "Petunia", "Gregory"),
a = c(67, 80, 64),
b = c(56, 90, 50)
)