-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.Rmd
1187 lines (873 loc) · 28.5 KB
/
index.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: "R Object Classes, Functions <br> and Coding Patterns"
author: "Mike Badescu, PhD"
date: "September 17, 2016"
output:
ioslides_presentation:
css: style.css
highlight: pygments
widescreen: yes
fig_caption: false
slidy_presentation:
css: style.css
revealjs::revealjs_presentation:
theme: white
highlight: default
transition: slide
rmdshower::shower_presentation:
self_contained: false
katex: true
theme: ribbon
ratio: 16x10
beamer_presentation:
theme: "Pittsburgh"
colortheme: "beaver"
---
## R Object Classes, Functions and Coding Patterns
**Mike Badescu, PhD**
@[MikeBadescu](https://twitter.com/MikeBadescu)
HTML Slides on GitHub Pages: <https://numeract.github.io/dallas-roo/>
Source Code on GitHub: <https://github.com/numeract/dallas-roo>
Dallas R Users Group
September 17, 2016
## About
**[Mike Badescu](http://mihaibadescu.net/)**
- PhD Economics, Lehigh University
- Experience: Economics, Finance, Statistics, Valuation
- Programming / main tools: R, Python, SQL, Spark, Scala
**[Numeract](http://numeract.com/)**
- Data Science and Economics / Finance consulting services
## Summary
1. R Object Classes
* S3
* S4
* Reference Classes & R6
2. R Functions and Coding Patterns
* dplyr & ggplot2
* immutability vs mutability
* pure functions
3. Open mic: how do you use R?
## Object-Oriented Programming (OOP)
Main Principles:
- Abstraction
+ identify essential characteristics that distinguish objects
- Encapsulation
+ hide implementation
- Modularity / Inheritance
+ promote code reuse (Don't Repeat Yourself - DRY)
- Polymorphism
+ single interface to entities of different data types
## Motivation {.build}
Setup
```{r setup, message=FALSE, warning=FALSE}
library(tibble); library(dplyr)
library(ggplot2); library(R6)
```
Regular polygons, first take
```{r}
triangle_size <- 6
square_size <- 4
hexagon_size <- 5
```
A common distinguishing feature: `size`
```{r}
triangle <- list(size = 6)
square <- list(size = 4)
hexagon <- list(size = 5)
```
## Motivation {.build}
Size alone is not sufficient:
```{r}
x <- list(size = 6)
# is x a square or a triangle?
```
Adding `sides`
```{r}
triangle <- list(sides = 3, size = 6)
square <- list(sides = 4, size = 4)
hexagon <- list(sides = 6, size = 5)
```
## Motivation
The objects `triangle`, `square` and `hexagon`:
- have the same **object attributes**
- belong to the same type of object / **class**: `regular_polygon`
We can perform similar actions: `print()`, `resize()`, `plot()`
- functions associated with objects are called **methods**
## Motivation {.build}
Let's implement a print function:
```{r}
print_rp <- function(rp) { # hmm... the 'print' name is taken
cat("Regular polygon with", rp$sides,
"sides of size", rp$size, "\n")
}
print_rp(triangle)
```
**Nice!**
A readable representation of the object is always welcome!
## Motivation {.build}
Let's implement `resize()`:
```{r}
resize <- function(rp, value = 1) {
rp$size <- rp$size * value
rp
}
print_rp(resize(triangle, 2))
print_rp(triangle) # the original object is unchanged
```
## Motivation
Or we can also use a **replacement function**:
```{r}
`size<-` <- function(rp, value = 1) { # note the name
rp$size <- rp$size * value
rp
}
triangle_copy <- triangle # let's work with a copy
size(triangle_copy) <- 2
print_rp(triangle_copy)
```
We modified the original / input object.
## Motivation {.build}
**Congratulations, we have a rudimentary OO model!**
*Anything missing?*
**How do I add a circle to the collection?**
- Circles are distant relatives of Regular Polygons
+ common elements like `size`
+ different elements such as `sides` and `print_rp()`
- This is **Inheritance**
**I would love to use `print()` instead of `print_rp()`!**
- This is **Polymorphism**
## S3
- S3 is an OO style based on **generic functions**
- In Java, Python:
+ `triangle.resize()`
+ the object decides which method to call
- In R:
+ `resize(triangle)`
+ a **generic function** used as dispatcher
- Main role: specific methods for print, summary, plot, predict, etc.
## S3 Classes
The class belongs to the object as an R attribute
```{r}
attr(triangle, "class") <- "regular_polygon"
triangle
```
## S3 Classes {.build}
Better: use `class()`
```{r}
class(square) <- "regular_polygon"
class(square)
class(hexagon) <- "regular_polygon"
class(hexagon)
```
## S3 Example
We have seen classes before
```{r}
df1 <- data.frame(a = 1:2, b = 3:4)
class(df1)
str(df1)
```
## S3 Example
Under the hood, statistical models are lists
```{r}
model <- lm(b ~ a, data = df1)
class(model)
str(model)
```
## S3 Example
More than one class is possible
```{r}
df2 <- as_data_frame(df1)
class(df2)
str(df2)
```
## S3 Example
Printing using the same function `print()`
```{r}
print(df1)
print(df2)
```
## S3 Example
We can `print()` the model, even if it is a different object
```{r}
print(model)
```
**How does this magic work?**
## S3 Generic Functions {.build}
Let's look at the code for `print()`
```{r}
print
```
`UseMethod()` is the dispatcher!
From `?UseMethod`:
> Method dispatch takes place based on the class(es) of the **first argument**
to the generic function or of the object supplied as an argument to `UseMethod`
## S3 Generic Functions {.build}
- Specific print methods are named `print.class_name()`, etc.
- `print()` calls the right method based on **the class of the first argument**
- How many "prints" are there?
```{r, eval=FALSE}
methods(print)
# ...
# [70] print.data.frame
# [71] print.Date
# [72] print.default
# ...
# [128] print.lm* <- * means non-visible
# ...
# [221] print.tbl_df*
# ...
```
## S3 Example {.build}
**Yeah? ... I want a `print()` method too!**
- The generic `print()` takes care of the dispatch
- All I need to do is to define `print.regular_polygon()`
```{r}
print.regular_polygon <- function(rp) {
cat("Regular polygon with", rp$sides,
"sides of size", rp$size, "\n")
}
print(triangle)
```
**Success!**
## S3 Methods {.build}
What methods are available for my `regular_polygon`?
```{r}
methods(class = "regular_polygon")
```
I want a `resize()` method!
Is there a `resize()` generic to take care of the dispatch?
```{r}
methods(resize)
```
## S3 Methods {.build}
Define the generic (it will overwrite the previous `resize()` function)
```{r}
resize <- function(x, ...) UseMethod("resize", x) # only one argument
resize.regular_polygon <- function(rp, value = 1) {
rp$size <- rp$size * value
rp
}
```
Testing with printing
```{r}
print(resize(triangle, 2))
```
This takes care of **Polymorphism**. What about **Inheritance**?
## S3 Inheritance
Inheritance requires to think about an hierarchy.
In our example, let's say that `circle` has its own class:
- inherits from `regular_polygon`
- we keep `size` but ignore (NA) `sides`
- we keep `resize()` but re-define `print()`
Alternative:
- new class
- define `size`
- define `resize()`and `print()`
## S3 Inheritance {.build}
```{r}
circle <- list(sides = NA, size = 1)
class(circle) <- c('circle', 'regular_polygon')
print(circle)
```
`circle` inherited everything from `regular_polygon`; define own `print.`
```{r}
print.circle <- function(rp) {
cat("Circle of size", rp$size, "\n")
}
print(circle)
```
Better!
## S3 Inheritance {.build}
Check inheritance
```{r}
inherits(circle, 'circle')
inherits(circle, 'regular_polygon')
```
Resize works by calling `resize` of the parent class
```{r}
print(resize(circle, 2))
```
## S3: *That's all folks!* {.build}
*(there are more details but we skip them today)*
**But wait ...**
You mean I can just take over objects, assign them any class?
```{r}
class(model)
class(model) <- c("Agent Smith", class(model))
class(model)
```
## S3 Problems {.build}
```{r}
class(df1)
class(df1) <- c("Agent Smith", class(df1))
class(df1)
```
_This code was responsible for Agent Smith taking over in Matrix Revolutions\*_
~__\*not a true fact__~
## S3 Problems
- R is weakly / dynamically typed
- Functions / Methods do not check for data type correctness
```{r, eval=FALSE}
class(model) <- "data.frame" # model was created by lm()
print(model)
# Error in `[.data.frame`(x, seq_len(n), , drop = FALSE) :
# attempt to set an attribute on NULL
```
## S4
- More formal
- Object attributes (**slots**) are clearly defined
+ Slots are accessed with `@` (not `$`)
+ Advanced: access to slots from Rcpp
- Object validation
- Methods have defined data types for arguments and output
+ can dispatch on multiple arguments
- Inheritance is clearly defined
## S4 Define
Use `setClass()`
```{r}
rm(list = ls()) # clean up
setClass(
Class = "Circle",
slots = representation(
size = "numeric"
)
)
```
## S4 New Instance {.build}
Use `new()`, must name the arguments
```{r}
circle <- new("Circle", size = 1.5)
circle
```
Type checking works
```{r, eval=FALSE}
circle2 <- new("Circle", size = "1.5")
# Error in validObject(.Object) :
# invalid class “Circle” object: invalid object for slot
# "size" in class "Circle": got class "character",
# should be or extend class "numeric"
```
## S4 Accessing Slots
Use `@` or `slot()`
```{r}
circle@size
slot(circle, 'size')
```
## S4 Modifying Slots {.build}
```{r}
circle@size <- 1.7 # you should do this only inside of a class method
circle@size
```
Type checking works again
```{r, eval=FALSE}
circle@size <- "1.7"
# Error in (function (cl, name, valueClass) :
# assignment of an object of class “character” is not valid for
# @‘size’ in an object of class “Circle”;
# is(value, "numeric") is not TRUE
```
## S4 Printing {.build}
- S4 printing is using the `show()` method; we need to overwrite it
- Use `setMethod()` with a function (which can be anonymous)
```{r}
Circle_show <- function(object) {
cat("Circle of size", object@size, "\n")
}
setMethod("show", "Circle", Circle_show)
print(circle)
```
## S4 Validity {.build}
- We want additional constraints, e.g., `@size` should be positive
- Additional validity is provided by a function we must supply
- Add validity within `setClass()` or by using `setValidity()`
+ return either `TRUE` or an error message
```{r, results='hide'}
Circle_validity <- function(object) {
if (object@size < 0) return("Size must be positive")
TRUE # return TRUE if all tests pass
}
setValidity("Circle", Circle_validity)
```
```{r, eval=FALSE}
circle2 <- new("Circle", size = -5)
# Error in validObject(.Object) :
# invalid class “Circle” object: Size must be positive
```
## S4 Validity {.build}
Modifying an existing S4 object is still permitted!!
```{r}
circle@size <- -5
circle
```
Force validity check
```{r, eval=FALSE}
validObject(circle)
# Error in validObject(circle) :
# invalid class “Circle” object: Size must be positive
```
Make the circle nice again
```{r}
circle@size <- 1.7
```
## S4 Accessors {.build}
- It's not a good idea to directly modify slots outside the object
- We will define accessor methods (since we are formal and all)
+ need to define the generic first `setGeneric()`
+ `standardGeneric()` used for S4 dispatching
```{r, results='hide'}
Circle_get_size <- function(object) object@size
setGeneric(name = "size",
def = function(object) standardGeneric("size"),
valueClass = "numeric")
setMethod("size", "Circle", Circle_get_size)
```
```{r}
size(circle)
```
## S4 Accessors {.build}
```{r, results='hide'}
Circle_set_size <- function(object, value) {
object@size <- value # modifies the object in the local scope
validObject(object) # force validation
object # the setter must return the object
}
setGeneric(name = "size<-",
def = function(object, value) standardGeneric("size<-"))
setMethod("size<-", "Circle", Circle_set_size)
```
Let's test it:
```{r}
size(circle) <- 2.5
size(circle)
```
## S4 Inheritance {.build}
Let's have `RegularPolygon` inherit from `Circle`
- need to add a slot for `sides`
```{r}
setClass(
Class = "RegularPolygon",
slots = representation(sides = "integer"), # only the new slot
contains = "Circle" # size inherited from Circle
)
```
```{r}
triangle <- new("RegularPolygon", sides = 3L, size = 3.5)
print(triangle)
```
*Bummer!*
## S4 Inheritance {.build}
Override `show()` for `RegularPolygon`
```{r}
RegularPolygon_show <- function(object) {
cat("Regular polygon with", object@sides,
"sides of size", object@size, "\n")
}
setMethod("show", "RegularPolygon", RegularPolygon_show)
print(triangle)
```
## S4 Inheritance
Test resizing
```{r}
(size(triangle) <- 3.8)
```
```{r}
is(triangle) # this is how we check for S4 classes
is(triangle, "Circle") # R cannot overcome poor design choices
```
We could overwrite validity and create more accessors, etc.
## S4 Problems {.build}
- Possible conflicts among multiple `setGeneric()` functions
- Pollution of the namespace with extra generics
- Difficult to debug
- Type checking
+ works well only with simple data types
+ `'numeric'` means `1.5` but also `c(1, 2, 3)`
+ in most cases one needs to define a validity function
+ made irrelevant if the data type is `list`
+ for data frames, it matters what is inside the data frame
[Frank Harrell](http://biostat.mc.vanderbilt.edu/wiki/Main/FrankHarrell)
(author of `Hmisc` and "problems with stepwise regression"):
> "If you love computer science more than you value your own time, use S4"
## Immutability in R
Almost all R objects are immutable => **copy-on-change**:
- a new object is created every time
- even when using replacement functions!
- R requires more time and more memory to copy the data
- S3 and S4 objects cannot modify themselves without a setter or re-assignment
```{r, eval=FALSE}
triangle <- expand(triangle, times = 2) # assume we created an expand method
```
- Although `assign()` can be used as a hack
- It's not as bad as it seems, lists and data frames copy only the modified
elements; they point to the old ones until a change is needed.
## Mutability in R {.build}
Except Environments:
- Similar to a `list` where each element is accessed by reference
- No new environment will be created at copy
- The old object is gone at re-assignment
```{r}
my_env <- new.env()
my_env$x <- 42
ls(my_env)
my_env$x
```
## The Environment Trick {.build}
- We can set a slot to be an environment
- Need to define an `initialize()` method, called by `new()`
+ each new object initializes its **own** environment
```{r, results='hide'}
setClass("Element",
slots = representation(x = 'numeric', my_env = 'environment')
)
setMethod("initialize", "Element",
function(.Object, ..., x=numeric(), my_env = new.env()) {
callNextMethod(.Object, x = x, my_env = my_env, ...)
}
)
```
## The Environment Trick {.build}
```{r}
el <- new("Element", x = 3)
print(el)
el@my_env$a <- 1
print(el@my_env$a)
```
## Reference Classes (RC) {.build}
Sometimes we want mutability, e.g., for bidirectional relationships
Alternative: **Reference Classes**
Reference Classes == S4 + Environment Trick + syntactic sugar
- Sometimes called **R5**, but this name causes confusion
- RC objects are mutable, they don’t use copy-on-change
- Use `$` to access methods; looks like Java and Python
- Still a hack, but a hidden hack
- It is rather slow
**Let's skip Reference Classes!** *(that was fast!)*
## R6
- Similar to Reference Classes, but it's faster and uses less memory
+ does not do type checking (one reason it is faster)
- Developed by Winston Chang at RStudio
- Shiny (from RStudio) uses R6 => production ready
- The R6 object is an environment, so it can store:
+ variables => object attributes
+ functions => methods
- R6 also supports:
+ public and private methods
+ inheritance across packages
+ `self$` notation as in Python
## R6 Basics
```{r}
rm(list = ls())
Circle <- R6Class(
classname = "Circle",
public = list( # public attributes
size = NULL, # no type!
initialize = function(size = NA) {
self$size <- size # good place to check types
},
print = function(...) cat("Circle of size", self$size, "\n"),
expand = function(value) {
self$size <- self$size * value # self modifying
}
)
)
```
## R6 Basics
```{r}
circle <- Circle$new(size = 6.1)
str(circle)
print(circle)
```
## R6 Basics {.build}
Access the object attributes
```{r}
circle$size
```
Access the object methods
```{r}
circle$expand(2) # look, no assignment
print(circle)
```
## R6 Private Members and Accessors
```{r}
PrivateCircle <- R6Class(
classname = "PrivateCircle",
private = list(
hidden_size = NULL),
public = list( # public attributes
initialize = function(size = NA) {
private$hidden_size <- size # good place to check data types
},
print = function(...) cat("Circle of size", private$hidden_size, "\n")),
active = list(
size = function(value) {
if (missing(value)) return(private$hidden_size)
else private$hidden_size <- value
}
)
)
```
## R6 Private Members and Accessors {.build}
```{r}
private_circle <- PrivateCircle$new(6.6)
private_circle$hidden_size # not visible
private_circle$size # getter
private_circle$size <- 7.7 # setter
private_circle
```
## R6 Inheritance
```{r}
RegularPolygon <- R6Class("RegularPolygon",
inherit = Circle,
public = list(
sides = NULL,
initialize = function(size = NA, sides = NA) {
super$initialize(size) # call parent's initialize
self$sides <- sides # take care of the new argument
},
print = function(...) {
cat("Regular polygon with", self$sides,
"sides of size", self$size, "\n")
}
)
)
```
## R6 Inheritance
```{r}
triangle <- RegularPolygon$new(size = 8.2, sides = 3)
str(triangle)
triangle
```
## R6 Inheritance {.build}
```{r}
triangle$size
triangle$expand(2)
triangle
```
We modified the original object
## R6 and the R user {.build}
As seen from Java, Python, etc. ...
- Finally, an Object Class that I understand!
- I understand public, private, `self$`
- I should use only R6!
... and that is a problem.
R users expect **copy-on-change** and may be confused by references.
## R6 and the R user
The following statement is not clear at the first glance to the R user:
```{r, eval=FALSE}
triangle$expand(2)
```
- I see `$`, is this a list or a data frame?
+ most users are not familiar with environments
- Are you calling a function from a list?
- So, what if you "expand" the triangle, **what do you get back?**
## R6 and the R user {.build}
Example from the package `openxlsx` (which uses Reference Classes)
```{r, eval=FALSE}
workbook <- createWorkbook()
addWorksheet(workbook, "Sheet 1")
```
- Does not follow the pattern `workbook$addWorksheet()`
- Internally, `addWorksheet()` calls `workbook$addWorksheet()`
- So, **did you or did you not** add a worksheet to `workbook`?
```{r, eval=FALSE}
names(workbook) # calls names.Workbook()
## [1] "Sheet 1"
```
## R6 and the R user {.build}
[Martin Morgan](https://www.bioconductor.org/about/core-team/)
(Bioconductor Project Lead), in reply to a
*"I'm a C++/Python developer"* point of view:
> "R's copy-on-change semantics leads me to expect that
>
> b = a
> slt(a) = 2
>
> leaves b unchanged, which S4 does (necessarily copying and thus with a
time and memory performance cost)."
>
> [...]
>
> "You either need to change your expectations, or use reference classes
(and change the expectations of your users)."
## R Object Classes - Which one to use? {.build}
You are using Bioconductor (S4 based) or a similar environment:
- Use S4
You must have reference objects due to the nature of the data
- Use R6 and avoid Reference Classes
- Manage user expectations: provide documentation, examples, etc.
You do not need reference objects:
- Use S3, if you have an option between S3 or S4
+ Google's R Style Guide advises against using S4
- **Better: use packages and a little of S3, e.g. for `print()`**
+ packages promote modularity and encapsulation
## R Functions and Coding Patterns {.build}
Experience is:
- knowing what to do
- knowing what **not** to do
- learning from making mistakes
- better, learning from other people's mistakes
The R Class Objects are far from perfect. So, what **really** works in R?
**What are some of the best practices in R?**
*warning: subjective views / experience follows*
## R Coding Style {.build}
- Follow a style guide, the most concise is Hadley's [style guide](http://adv-r.had.co.nz/Style.html)
- Break complex lines into components and pick meaningful names
+ one step closer to self-documenting code
```{r, eval=FALSE}
df2 <- df[grepl(
'^[0-9]{5}$', df$zip_code), ] # usually the pattern is more complex
# vs
zip5_pattern <- '^[0-9]{5}$'
zip5_mask <- grepl(zip5_pattern, sales$zip_code)
sales_with_zip <- sales[zip5_mask, ]
```
- Brandon Rhodes: [The Naming of Ducks](http://rhodesmill.org/brandon/talks/#naming-of-ducks)
(video and slides)
+ It's about Python, but it applies to R as well
## dplyr {.build}
If you are learning R ...
- You are going to see many examples using old R functions,
such as `subset()`, `plot()`, etc.
- Instead use `dplyr`, `ggplot2` and other packages from the [tidyverse](https://blog.rstudio.org/2016/09/15/tidyverse-1-0-0/)
+ they promote clear and modular code
- Make use of pipe symbol `%>%` from [magrittr](https://cran.r-project.org/package=magrittr),
available in `dplyr`
For a detailed example, have a look at Zev Ross: