-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathr.rmd
6832 lines (4887 loc) · 165 KB
/
r.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 cheatsheet"
author: Emil Rehnberg
bibliography: refs.bib
date: "`r Sys.Date()`"
csl: shiki.csl
output:
pdf_document:
highlight: zenburn
html_document:
toc: TRUE
toc_float: TRUE
css: styles.css
---
```{r set-options, echo=FALSE, cache=FALSE}
options(width = 200)
```
```{r echo=FALSE, eval=FALSE}
library(rmarkdown); require(shiny)
rmdFilePath <- "r.rmd"
allexamples <- FALSE
rmarkdown::render(rmdFilePath, output_format="html_document") # "all_document"
# TODO
# - try out Bundler for R -- https://github.com/robertzk/lockbox
```
```{r, eval=FALSE, echo = FALSE}
devtools::install_github('cran/colorout')
```
```{r echo=FALSE, message=FALSE}
set.seed(308)
require(colorout)
require(dplyr)
require(tidyr)
require(magrittr)
require(ggplot2)
```
```{r "initiate polymorphic exclude", echo = FALSE}
include <- function(obj, elms) UseMethod("include")
exclude <- function(obj, elms) UseMethod("exclude")
```
# 目的
cheatsheet for R. it's a place to dump typical annotated R-code.
# Datasets {.tabset .tabset-fade .tabset-pills}
## Overview
`R` has several open datasets
## numerical
```{r}
library(magrittr)
airquality %>% str
mtcars %>% str
USArrests %>% str
```
## Time-series
```{r}
AirPassengers %>% str
Nile %>% str
freeny %>% str # with numerical variables also!
```
## factors
```{r}
CO2 %>% str
ChickWeight %>% str # Ord.factor ordinal factor!
esoph %>% str # multiple Ord.factor
iris %>% str
npk %>% str
warpbreaks %>% str
# library(randomForest)
# data(imports85)
# imports85 %>% str # factors & ord.factor
data(quine, package = "MASS")
quine %>% str
```
## lists
```{r}
Harman23.cor %>% str
```
## tables
multidimensional tables!
```{r}
Titanic %>% str
```
## Survival data suitable data
```{r}
data("GBSG2", package = "TH.data")
GBSG2 %>% str
with(GBSG2, { survival::Surv(time, cens) }) %>% head(10)
```
# R-language design {.tabset .tabset-fade .tabset-pills}
## Overview
Section for R-language design and concepts. Packages, code, data loading
## loading / unloading packages
in order to attach / load / require packages use `library` (or `require` if you like problems).
to detach / unload / remove a package from a session you can use `detach`
```{r}
exists("is_in") # from magrittr package
detach(package:magrittr)
exists("is_in")
library(magrittr)
exists("is_in")
```
## error handling
use `tryCatch`
with error handler
```{r "error / exception handling", echo = TRUE}
library(magrittr)
myError <- simpleError("エッラー!")
tryCatch({
print(1);
stop(myError)
print(2)
}, error = function(err){
message("error function messages:")
(err %>% print)
}, finally = {
print("always finish run with finally()")
message("finished tryCatch")
})
```
with warning handler
```{r}
tryCatch({
print(1)
warning("ACHTUNG! ACHTUNG!")
print(2)
}, warning = function(war){
message("warning function messages:")
(war %>% print)
}, finally = {
print("always finish run with finally()")
message("finished tryCatch")
})
```
`stop` returns exit code 1 (check with `$?` in ruby and `$?.exitstatus` especially)
you can also use the `tools` package. but `pskill` does not returns a 0 exit status. `pskill` seems to be rather rough around the edges, use with care.
```{r}
# tools::pskill(Sys.getpid(), tools::SIGINT)
```
## Control Flow
E.g. if / else statements
```{r "control flow, all the below can be parsed"}
if(1 == 2)
print("1 == 2") else
if(2 == 2)
print("2 == 2") else
print("ALL FALSE")
if(1 == 2) {
print("1 == 2")
} else if(2 == 2) {
print("2 == 2")
} else {
print("ALL FALSE")
}
if(1 == 2) {
print("1 == 2")
} else {
if(2 == 2) {
print("2 == 2")
} else {
print("ALL FALSE")
}
}
```
## ellipsis
`...` / ellipsis or "dot-dot-dot"
use an arbitrary number of arguments to a function
```{r}
a <- c(1, 2, NA, 4, NA)
b <- c(NA, NA, NA, 5, 6)
c <- c(7, 8, NA, 9, 10)
```
catch the arguments in a list
```{r}
elTrail1 <- function(...) list(...)
```
catch the arguments in a data frame
```{r}
elTrail2 <- function(...) data.frame(...)
```
extract the first argument
```{r}
elTrail3 <- function(...) ..1
```
extract the second argument
```{r}
elTrail4 <- function(...) ..2
```
## Environments
```{r}
exists("abc")
abc <- 2
exists("abc")
exists("pi", envir = emptyenv())
exists("glm", envir = as.environment("package:base"))
exists("glm", envir = as.environment("package:stats"))
```
## dump object to executable R code
`dput` is your friend. NOTE: not suitable for S4 objects. try `writeRDS` or `save` for that.
there's some gotchas though. When you're dumping a factor - the output might end up crazy long. Use `as.character` to get what you're looking for.
```{r "dput gotcha"}
library(dplyr)
(USArrests %<>% mutate(state = USArrests %>% row.names %>% as.factor)) %>% str
USArrests$state %>% head(2) %>% dput
USArrests$state %>% head(2) %>% as.character %>% dput
```
## parse CL args
parsing command line arguments / parameters
- use `#!/usr/bin/env Rscript` on top of the executable file (`tca.r` let's say)
- call `./tca.r --args a=1 name=\'Billy\'`
- use the `commandArgs`, `parse` and `eval` functions to read the parameters into your script
- sometimes if `trailingOnly` is set, `--args` is still in there
```{r "commandArgs"}
library(magrittr)
arguments <- c("a=1", "name=\'Billy\'") # commandArgs(trailingOnly = TRUE)
for(argument in arguments){
eval(parse(text = argument))
}
```
into a `data.frame`. This works but then all columns are strings
```{r "command line arguments into data.frame"}
arguments %>% strsplit("=") %>% sapply(function(strings) purrr::set_names(strings[2], strings[1]) )
```
use `jsonlite` instead by sending in JSON data. E.g. executing:
`./predict-co2uptake '[{"Type": "Quebec", "Treatment": "nonchilled", "conc": 350}]'`
on the command line
```{r "command line arguments into data.frame using jsonlite"}
jsonlite::fromJSON('[{"Type": "Quebec", "Treatment": "nonchilled", "conc": 350}]') %>% str
```
## Object system {.tabset .tabset-fade .tabset-pills}
### Overview
R has a S3 and S4 Object system. S3 is preferred using polymorphism.
Ref: [adv-R](http://adv-r.had.co.nz/OO-essentials.html)
### Base types
R "base types" are like a C struct, has 1) object contents and 2) a type. This is not an object system as you can't add objects to it.
```{r}
f <- function() NULL
typeof(f) # [1] "closure"
is.function(f)
typeof(sum) # [1] "builtin" # for primitive functions
is.primitive(sum)
```
use `pryr::otype` to understand what kind of system an object follows
```{r}
pryr::otype(character()) # [1] "base"
pryr::otype(integer()) # [1] "base"
pryr::otype(numeric()) # [1] "base"
pryr::otype(matrix()) # [1] "base"
pryr::otype(list()) # [1] "base"
pryr::otype(c()) # [1] "base"
pryr::otype(factor()) # [1] "S3"
pryr::otype(ts()) # [1] "S3"
pryr::otype(data.frame()) # [1] "S3"
as.Date("1999-01-01") %>% pryr::otype() # [1] "S3"
df <- data.frame(x = 1:5, y = LETTERS[1:5])
pryr::otype(df)
pryr::otype(df$x)
pryr::otype(df$y) # factors are S3
pryr::otype(mean)
```
use `pryr::ftype`
```{r}
pryr::ftype(`%in%`)
pryr::ftype(sum)
pryr::ftype(t.data.frame)
pryr::ftype(t.test) # Tricky!
pryr::ftype(writeLines)
pryr::ftype(unlist)
pryr::ftype(mean)
methods(mean)
pryr::ftype(mean.Date)
```
### S3
#### methods
- query all methods for a S3 generic function
- query all methods S3 function available for a class
```{r, ""}
pryr::ftype(mean)
methods(mean)
methods(class = "Date")
```
#### generic function "UseMethod"
TODO: add example where you pass more arguments
base for `R`'s S3 object system using polymorphism, switching function (function / method dispatch) on the class of the called object.
```{r, "UseMethod"}
asEmpty <- function(object) UseMethod("asEmpty")
asEmpty.integer <- function(object) integer(0)
asEmpty.character <- function(object) character(0)
methods(asEmpty)
1:3 %>% asEmpty
letters %>% asEmpty
```
#### constructor function
example. think the factor and `data.frame` functions
```{r}
foo <- function(x) {
if (!is.numeric(x)) stop("X must be numeric")
structure(list(x), class = "foo")
}
```
#### Use-case
adding custom classes to objects and using polymorphism
```{r}
mkNameFeatures <- function(obj) UseMethod("mkNameFeatures")
mkNameFeatures.se <- function(names) data.frame(name = names, namesCount = names %>% strsplit(" ") %>% purrr::map_dbl(length))
mkNameFeatures.ja <- function(names) data.frame(name = names, hasSpace = names %>% grepl(pattern = " ") )
initClass <- function(obj, cls) obj %>% structure(class = cls %>% append(class(obj)) %>% unique)
jaNames <- c("田中角栄", "杉本 レイ", "上杉謙信") %>% initClass("ja")
seNames <- c("Emil Erik Alexis Rehnberg", "stella", "balle AF raggare") %>% initClass("se")
jaNames %>% mkNameFeatures
seNames %>% mkNameFeatures
jaNames %>% mkNameFeatures %>% initClass("ja")
```
# Standard Libraries {.tabset .tabset-fade .tabset-pills}
## Overview
Looking at functions from e.g. `base` and `stats` packages that are loaded by default R.
## Allocation
as in allocation of empty objects / place holders
```{r "place holder allocation"}
vector("integer", 6)
vector("double", 7)
vector("character", 8)
vector("logical", 3)
```
## File Manipulation
Working with files. Checking existance, copy `cp`, removing `rm`, appending etc.
```{r "file-manipulation"}
library(magrittr)
tmpDir <- file.path("", "tmp", "r-file-manipulation")
dir.exists(tmpDir)
dir.create(tmpDir)
dir.exists(tmpDir)
list.files(tmpDir) # return empty character atomic vector
filePath1 <- tmpDir %>% file.path("A.md")
filePath2 <- tmpDir %>% file.path("B.md")
filePath3 <- tmpDir %>% file.path("C.md")
cat("file A\n", file = filePath1)
file.exists(filePath2)
cat("file B\n", file = filePath2)
file.exists(filePath2)
file.append(filePath1, filePath2)
file.info(filePath1)
# file.show(filePath1) # opens file, only run if in an interactive session
file.copy(filePath1, filePath3)
file.remove(filePath1, filePath2, filePath3)
file.remove(tmpDir) # works on EMPTY directories
```
## Extract
aka `[`. Use `drop` to keep the matrix.
```{r "base:extract"}
(m <- matrix(1:9, nrow = 3, dimnames = list(c("a", "b", "c"), LETTERS[1:3])))
m[1, ] # first row of m (atomic vector)
m[1, , drop = FALSE] # first row of m still as matrix
```
## replications
replicate elements of vectors and lists
```{r "base::rep"}
rep(1:4, 2)
rep(1:4, each = 2) # not the same.
rep(1:4, c(2,2,2,2)) # same as second.
rep(1:4, c(2,1,2,1))
rep(1:4, each = 2, len = 4) # first 4 only.
rep(1:4, each = 2, len = 10) # 8 integers plus two recycled 1's.
rep(1:4, each = 2, times = 3) # length 24, 3 complete replications
(x <- LETTERS[1:4] %>% setNames(letters[1:4]) %>% as.factor)
rep(x, times = 2)
rep(x, each = 2)
rep.int(x, times = 2) # no names
rep(x, len = 10)
rep_len(x, length.out = 10) # no names
```
## iterate over data frame variables
use `base::seq_along` in a for loop to iterate over a data frame's variables / columns
```{r}
(scaledArrests <- USArrests) %>% head
for(i in seq_along(USArrests)){
scaledArrests[[i]] <- scale(USArrests[[i]] %>% as.numeric) %>% round(3)
}
scaledArrests %>% head
```
be aware that the same thing (minus the row names) can be acheived much more nicely with `sapply`
```{r}
USArrests %>% dplyr::select(-state) %>% sapply(scale) %>% as.data.frame %>% head
```
## reduce function
`base::Reduce`
Common Higher-Order Functions in Functional Programming Languages (similar to Common Lisp's `(reduce)`)
Simple example
```{r}
add <- function(x) Reduce("+", x)
add(1:4)
```
Custom cumulative function. Approximation for pi. `right` argument determines if process starts from the right (or from the left).
```{r}
c(3, 7, 15, 1, 292) %>%
Reduce(f = function(incr, acc) incr + 1 / acc, right = TRUE)
```
## pattern matching
`base::switch`
exact pattern matching in R
```{r}
centre <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
centre(x, "median")
centre(x, "trimmed")
```
## split df to list
e.g. split a `data.frame`, rows / observations to list. NOTE: second argument is a "group" e.g. `1:10`. If you in this case have a data frame with ten rows, each row will be in an entry in the returned list.
```{r "listify observations to iterate over rows"}
data.frame(a = 1:10
,b = 11:20
,c = 51:60) %>%
split(seq(nrow(.)))
```
or by some other grouping
```{r}
split(airquality, airquality$Month)
```
## work inside closed data environment
`base::with` and `base::within`
```{r}
with(airquality, { cor(Temp, Ozone, use = "complete") })
aq <- within(airquality, { # Notice that multiple vars can be changed
lOzone <- log(Ozone)
Month <- factor(month.abb[Month])
cTemp <- round((Temp - 32) * 5/9, 1) # From Fahrenheit to Celsius
S.cT <- Solar.R / cTemp # using the newly created variable
rm(Day, Temp)
})
head(aq)
```
## system information
invoke system calls / command line. check system info and library / package info.
```{r "OS calls"}
system("date")
system("echo $USER")
Sys.getenv()
Sys.info() %>% as.matrix
.libPaths()
```
useful for installing packages to a specific library / folder: `install.packages("magrittr", lib = .libPaths()[2])`
default lib parameter is `.libPaths()[1]` which tends to be user specific
`R_LIBS_USER` sets the personal library for a user.
`Sys.unsetenv("R_LIBS_USER")` can unset this so you use a global library path instead
R home
```{r}
R.home()
Sys.getenv("R_HOME")
```
## Citation
```{r message=FALSE}
require(magrittr)
```
```{r}
citation() %>% toBibtex # defaults to R-documentation
citation("magrittr") %>% toBibtex
```
## package version
check the version of an available package
```{r "packageVersion"}
packageVersion("magrittr")
```
## set reference level
`stats:relevel`
to set reference/base/stardard/default level for e.g. a logistic regression use `relevel` with the `ref` flag
```{r}
warpbreaks %>% str
warpbreaks$tension <- relevel(warpbreaks$tension, ref = "M")
warpbreaks %>% str
```
## scientific notation
print in scientific notation
```{r}
library(magrittr)
1234567890123
123456
123456 %>% format(scientific = TRUE)
```
you can also tinker with the `options(scipen=)` option
## print declared variable
use parentheses to return / print result during variable declaration
```{r}
(a <- 1)
a
```
## dicotomize
discretize continuous variable. (turn continuous variable discrete)
```{r}
Z <- stats::rnorm(10000)
table(cut(Z, breaks = -6:6))
breaks <- c(-3, 1, 5) # one more break than labels
labels <- c("low", "high")
U <- runif(10, min=-3, max=5)
cut(U,
breaks = breaks,
labels = labels,
ordered_result = TRUE, # for ordered factors (not always well supported)
include.lowest = TRUE)
```
## matching
`match` et. al match on the first character forward.
```{r}
1:10 %in% c(1,3,5,9)
charmatch("m", c("mean", "median", "mode"))
charmatch("med", c("mean", "median", "mode"))
```
#### using grep
matching character strings/vectors using regexes or character strings. use `value` flag to return the actual matches and not the index.
```{r}
txt <- c("arm", "foot", "lefroo", "bafoobar")
grep("foo", txt)
grep("foo", txt, value = TRUE)
```
matching two exact expressions, either or
```{r}
library(magrittr)
txt <-
c( "The", "licenses", "for", "most", "software", "are", "designed", "to", "take", "away", "your", "freedom", "to", "share"
,"and", "change", "it.", "", "By", "contrast,", "the", "GNU", "General", "Public", "License", "is", "intended", "to"
,"guarantee", "your", "freedom", "to", "share", "and", "change", "free", "software", "--", "to", "make", "sure"
,"the", "software", "is", "free", "for", "all", "its", "users")
```
returns index
```{r}
txt %>% grep(pattern = "ak")
txt %>% grep(pattern = "ak|an")
```
returns value
```{r}
txt %>% grep(pattern = "ak", value = TRUE)
txt %>% grep(pattern = "ak|an", value = TRUE)
```
returns logical (grep logical)
```{r}
txt %>% grepl(pattern = "ak")
txt %>% grepl(pattern = "ak|an")
```
matching on multiple character strings inside the same character string
```{r}
txt %>% grep(pattern = "s.*ar", value = TRUE)
txt %>% grep(pattern = "ra", value = TRUE)
txt %>% grep(pattern = "n.*ra", value = TRUE)
```
matching on end of string by using dollar sign `$` at the end of the pattern
```{r}
strs <-
c("Product.Age", "Salesforce.Center", "Category", "Standard.Months",
"FY15.10", "FY15.11", "FY15.12", "FY16.01", "FY16.02", "FY16.03",
"FY16.04", "ofc-FY16.05", "ofc-FY16.06", "FY16.07", "ofc-FY16.08", "FY16.09",
"FY16.10", "FY16.11", "FY16.12", "FY17.01", "FY17.02", "FY17.03",
"FY17.04", "FY17.05", "FY17.06", "FY15.09.1",
"FY15.10.1", "FY15.11.1", "FY15.12.1", "FY16.01.1", "FY16.02.1",
"FY16.03.1", "FY16.04.1", "ofc-FY16.05.1", "ofc-FY16.06.1", "FY16.07.1",
"FY16.08.1", "FY16.09.1", "FY16.10.1", "ofc-FY16.11.1", "ofc-FY16.12.1",
"FY17.01.1", "FY17.02.1", "FY17.03.1", "FY17.04.1", "FY17.05.1",
"FY17.06.1")
strs %>% grep(pattern = "(FY\\d{2}).(\\d{2})$", value = TRUE)
```
matching on start of string by using caret `^` at the start of the pattern
```{r}
strs %>% grep(pattern = "^(FY\\d{2}).(\\d{2})$", value = TRUE)
```
## padding
padding with zeros
```{r}
sprintf("%04d", 20)
```
or less stable
```{r}
sprintf("%02s", c("10", "8", "12"))
```
case with hours and minutes, similar to a clock
```{r "sprintf clock"}
sprintf("%02s:%02s", 0:5, 15)
sprintf("%02s:%02s", 0:5, c(5,25,55)) # not expected
sprintf("%02s:%02s", rep(0:5, each = 3), c(5,25,55)) # expected
minutesAsClock <-
function(minutes)
sprintf( "%02s:%02s"
,minutes %>% magrittr::divide_by_int(60)
,minutes %>% magrittr::mod(60)) # modulo `%%`
(0:12*60+40) %>% minutesAsClock
```
Windows
```{r "sprintf on windows"}
sprintf("%02s", c("10", "8", "12")) # doesn't return what you'd expect on windows >.<
# sprintf("%02d", c("10", "8", "12")) # however this does! using `d`
# not sure it works as intended on Unix systems though
```
## substr
can extract characters based on position
```{r}
c('201611', '201304') %>% substr(5,6)
c('201611', '201304') %>% substr(1,4)
```
Can be working similar to T-SQL's `LEFT`-function. No need to use regex
Can also be thought of as deleting parts of strings / characters.
## numerical characteristics of the machine
`.Machine` has a lot of numerical characteristics
e.g. the rounding error
```{r}
.Machine$double.eps
.Machine
```
## setting names for arrays
use `stats::setNames`
```{r}
setNames( 1:3, c("foo", "bar", "baz") )
setNames( 1:3, nm = c("foo", "bar", "baz") )
setNames( nm = c("foo", "bar", "baz") ) # Special case
```
or `base::structure`; NOTE: you need to name any arguments, unlike `setNames`.
```{r}
structure( 1:3, nm = c("foo", "bar", "baz") ) # don't use `nm`
structure( 1:3, names = c("foo", "bar", "baz") )
# structure( 1:3, c("foo", "bar", "baz") ) # Error in structure(1:3, c("foo", "bar", "baz")) : attributes must be named
```
## scale
for normalizing / standardizing variables in `data.frame`
`scale` takes three arguments, the data, center and scale.
- `center` what you subtract from the values (unless set to `FALSE`). Default is the mean of the column in question.
- `scale` is the demoninator (unless set to `FALSE`). Default is the standard deviation.
```{r "scale function"}
airquality %>% summary
airquality %>% scale %>% summary # NOTE: the means and symmetrics between min/max
```
function to scale columns to `[0,1]` unit range
TODO: add scale function to go between `[-1,1]`
```{r}
unitScale <- function(dta)
scale(dta
,center = dta %>% purrr::map_dbl(min, na.rm = TRUE)
,scale = dta %>% purrr::map(range, na.rm = TRUE) %>% purrr::map_dbl(diff)
)
airquality %>% unitScale %>% summary
```
# Helpers {.tabset .tabset-fade .tabset-pills}
### Overview
Section for good helper functions.
### exclude
delete / remove / exclude / reject elements from a vector
```{r "vector remove element(s)"}
exclude.default <- function(vctr, elements) vctr[! vctr %in% elements]
a <- c("master", "of", "puppets")
a %>% exclude(c("of", "master"))
```
### Curry
perform currying in R with the `functional` package. Or just use
```{r}
Curry <- function(FUN, ...){
.orig <- list(...)
function(...) do.call(FUN, c(.orig, list(...)))
}
```
### isEmpty
checks if list / atomic vector (array) is empty
```{r}
library(magrittr)
isEmpty <- function(obj) UseMethod("isEmpty")
isEmpty.default <- function(obj) obj %>% length %>% equals(0)
isEmpty.data.frame <- function(dtf) dtf %>% nrow %>% equals(0)
isEmpty.tbl <- function(obj) obj %>% as.data.frame %>% isEmpty
isEmpty.character <- function(chrs) chrs %>% `==`("")
integer(0) %>% isEmpty
1:3 %>% isEmpty
list() %>% isEmpty
1:3 %>% as.list %>% isEmpty
data.frame(price = integer(0)) %>% isEmpty
data.frame(price = 1:3) %>% isEmpty
"" %>% isEmpty
'' %>% isEmpty
'a' %>% isEmpty
```
### isNonEmpty
checks if list / atomic vector (array) is non-empty
```{r}
library(magrittr)
isNonEmpty <- function(obj) UseMethod("isNonEmpty")
isNonEmpty.default <- function(obj) obj %>% length %>% is_greater_than(0)
isNonEmpty.data.frame <- function(obj) obj %>% nrow %>% is_greater_than(0)
isNonEmpty.tbl <- function(obj) obj %>% as.data.frame %>% isNonEmpty
integer(0) %>% isNonEmpty
1:3 %>% isNonEmpty
list() %>% isNonEmpty
1:3 %>% as.list %>% isNonEmpty
data.frame(price = integer(0)) %>% isNonEmpty
data.frame(price = 1:3) %>% isNonEmpty
```
### asQuoted
put single quotes around the argument. This is useful mainly for the underscore variants of `dplyr` functions.
```{r "asQuoted"}
asQuoted <- function(arg) paste0("'", arg, "'")
set.seed(12)
threshold <- .7
data.frame(a = runif(10)) %>% filter_(paste("a > ", threshold %>% asQuoted))
```
### compact
similar to ruby's `compact`.
```{r}
library(magrittr)