-
Notifications
You must be signed in to change notification settings - Fork 2
/
UsefulCode2.Rmd
2108 lines (1696 loc) · 54.7 KB
/
UsefulCode2.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: Useful R code 2
author: |
| Matthew Malishev
| @darwinanddavis
#bibliography:/Users/malishev/Documents/Melbourne Uni/Thesis_2016/library.bib
fontsize: 10
geometry: margin=1in
documentclass: article
linkcolor: pink
urlcolor: blue
citecolor: red
always_allow_html: yes
output:
html_document:
highlight: tango
code_folding: show
toc: yes
toc_depth: 4
number_sections: no
toc_float: yes
md_document:
variant: markdown_github
pdf_document:
includes:
in_header: # add .tex file with header content
highlight: tango
template: null
toc: yes
toc_depth: 4
number_sections: false
fig_width: 4
fig_height: 5
fig_caption: true
df_print: tibble
citation_package: biblatex # natbib
latex_engine: xelatex #pdflatex # lualatex
keep_tex: true # keep .tex file in dir
word_document:
highlight: tango
keep_md: yes
pandoc_args: --smart
#reference: mystyles.docx
toc: yes
toc_depth: 4
inludes:
before_body: before_body.tex
subtitle:
tags:
- nothing
- nothingness
params:
dir: "/Users/malishev/Documents/Melbourne Uni/Programs/R code/UsefulCode"
date: !r Sys.Date()
version: !r getRversion()
email: "matthew.malishev [at] gmail.com"
doi: https://github.com/darwinanddavis/UsefulCode
classoption: portrait
# ^['https://github.com/darwinanddavis/UsefulCode'] # footnote
vignette: >
%\VignetteIndexEntry{Useful R code}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: "all"} } });
</script>
```{r echo = FALSE}
library(rmarkdown)
# setwd("")
# f <- list.files()[1]
# render(f, output_format='pdf_document')
# render(f, output_format='pdf_document')
```
```{r, set-options, echo = FALSE, cache = FALSE}
options(width=100)
knitr::opts_chunk$set(
eval = F, # run all code
# echo = FALSE, # show code chunks in output
comment = "",
tidy.opts=list(width.cutoff=100), # set width of code chunks in output
tidy=TRUE, # make output as tidy
message = FALSE, # mask all messages
warning = FALSE, # mask all warnings
size="small" # set code chunk size
)
# https://github.com/ucb-stat133/stat133-fall-2016/blob/master/hws/hw02-tables-ggplot.Rmd
knitr::opts_knit$set(root.dir=paste0(params$dir,"/")) # set working dir
setwd(paste0(params$dir,"/")) # for running just in R not knitr
```
\
Date: `r params$date`
`R` version: `r params$version`
*Corresponding author: `r params$email`
This document can be found at `r params$doi`
\newpage
## Overview
Same deal as Useful Code, but the second instalment because the first one has too much stuff in it and now runs slow.
### Animations
Typing text animation based on typed.js
<!-- https://awesomeopensource.com/project/JohnCoene/typed -->
```{r, animate1}
remotes::install_github("JohnCoene/typed")
require(typed)
typed("Hello")
typed("Emphasis word <span style ='color: red;'>with html</span>.", contentType = "html")
typed(list(shiny::h3("First sentence."), shiny::h4("Second sentence")), typeSpeed = 2)
```
### Colour palettes
`Colorspace`
```{r, col1, eval=T}
require(colorspace)
hcl_palettes(plot = TRUE) # show all palettes
```
```{r, col1_}
# https://cran.r-project.org/web/packages/colorspace/vignettes/colorspace.html
require(colorspace)
q4 <- qualitative_hcl(4, palette = "Dark 3") # discrete
s9 <- sequential_hcl(9, "Purples 3") # continuous
# for ggplot
scale_color_discrete_sequential(palette = "Purples 3", nmax = 6, order = 2:6)
# for colospace functions:
# hcl_palettes() %>% str
# hcl_palettes()["type"]
```
Neon colour palettes
```{r, col2,eval=T}
# https://www.shutterstock.com/blog/neon-color-palettes
neon1 <- c("#3B27BA","#FF61BE","#13CA91","#FF9472")
neon2 <- c("#FFDEF3","#FF61BE","#3B55CE","#35212A")
neon3 <- c("#FEA0FE","#F85125","#02B8A2","#535EEB")
neon4 <- c("#535EEB","#001437","#C6BDEA","#FFAA01")
scales::show_col(c(neon1,neon2,neon3,neon4))
```
Hexadecimal color code for transparency
See https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4.
```{r,col3}
require(colorspace)
require(stringr)
colv <- c("#004616",sequential_hcl(5,"Lajolla"))
str_sub(colv,0,1) <- "#66" # add alpha opac to col vector
```
Lighten/darken colours
<!-- https://colorspace.r-forge.r-project.org/articles/manipulation_utilities.html -->
```{r, col4}
require(colorspace)
"#EFEFEF" %>% lighten(0.2)
"#EFEFEF" %>% darken(0.2)
```
Colour gradient palettes for multi coloured lines/paths/routes
```{r, col5, eval =T}
require(colorspace)
require(ggplot2)
require(dplyr)
# data
nn <- 100
df <- data.frame("x" = 1:nn, "var1" = sample(200,nn,replace=T))
# option 1
colp <- "#f4d29f"
colv <- colorRampPalette(colors = c(colp %>% darken(0.2), colp, colp %>% lighten(0.2)))
colpal <- colv(df$var1 %>% unique %>% length)
# option 2
colpal <- sequential_hcl(df$var1 %>% unique %>% length,"Purple-Blue",power = 0, l = 50)
# plot
ggplot() +
geom_line(data = df, aes(1:nrow(df),var1, color = var1), size = 1, show.legend = F,lineend = "round",linejoin = "round") +
scale_color_gradientn(colours = colpal, aesthetics = "col")
```
Alphanumeric hexcodes with opacity
<!-- https://stackoverflow.com/questions/23201134/transparent-argb-hex-value -->
In `HTML/CSS` (browser code), the format is #RRGGBBAA with the alpha channel as last two hexadecimal digits eg. Mapbox fill colour for both manual colour and df variable. Otherwise, the alpha channel is the last two digits.
Example: For 85% white, you would use #D9FFFFFF. Here 85% = "D9" & White = "FFFFFF"
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
Change colour palette
### Chord diagrams
<!-- from olympics.R data viz eg -->
```{r, chord1}
require(circlize,reshape2,tidyr)
# use either melted df or table
dtab <- df %>% # opt1
dcast(var1~var2, fill = 0) %>%
melt() %>%
uncount(value)
dtab <- df %>% table() # opt2
# plot pars
par(mar = rep(2, 4),mfrow = c(1, 1))
circos.clear()
circos.par(start.degree = -180, # chord setup
gap.degree = 2, track.margin = c(-0.1, 0.1),
points.overflow.warning = F,
track.height = 0.2)
circos.par(cell.padding =c(0.02, 0, 0.02, 0))
# plot
chordDiagram(dtab,
grid.col = colpal,
transparency = 0.3,
directional = 1, # 1 = link origin is from sectors
diffHeight = -0.05,
# link.border = "#FFFFFF",
annotationTrack = c("grid"
# ,"name" # to check name placment
),
annotationTrackHeight = c(0.05, 0.1),
big.gap = 5, small.gap = 2, # gaps between sectors
link.sort = F, # order links are drawn
link.decreasing = T, # define link overlap
link.largest.ontop = T,
preAllocateTracks = list(track.height = 0.1)
# symmetric = F
# scale = F # weight links equally
)
```
Add custom labels
```{r, chord2}
# after initiating plot (see above)
ylim <- 0.85
im <- 0.6
circos.track(track.index = 1,
panel.fun = function(x,y){ # add text labels
sector_index = get.cell.meta.data("sector.numeric.index")
circos.text(x = CELL_META$xcenter,
y = ylim,
# remove medal labels
labels = CELL_META$sector.index,
facing = "clockwise", niceFacing = T, cex = im, col = col_lab
)}
, bg.border = NA) # set bg to NA
```
Use custom raster images as sector labels
```{r, chord3}
require(magick)
# create img labels
img <- "img.png"
img_convert <- function(img){
imgr <- img %>% magick::image_read() %>% as.raster() # convert img to raster layer
imgr[imgr == "#002163ff"] <- col_lab # change main img color
imgr %>% return()
}
imgl <- c(as.list(rep(img,dtab$var1 %>% unique %>% length))) # match imgs to no of chord sectors
imglist <- lapply(imgl,img_convert) # apply convert to raster func
imgtab <- c(as.list(rep(NA,n)),imglist) # optional: rm first n images from sectors
names(imgtab) <- get.all.sector.index() # get names from plot sector indices
ylim <- 3
im <- "7mm"
circos.track(track.index = 1,
for(si in seq_along(get.all.sector.index())){ # apply event img to each sector index
circos.raster(x = CELL_META$xcenter, #0.5,
y = ylim,
sector.index = get.all.sector.index()[si],
image = imgtab[[si]], # add image
width = im, height = im,
facing = "downward")
},
panel.fun = function(x,y){ # add text labels
circos.text(x = CELL_META$xcenter, # center label
y = ylim/3,
labels = CELL_META$sector.index,
facing = "clockwise", niceFacing = T,
cex = 0.5, col = col_lab,
adj = c(0, 0.5) # nudge xy position
)}
, bg.border = NA) # set bg to NA
```
### D3
Links
- [](https://github.com/d3/d3/wiki/Gallery)
- [](https://bl.ocks.org/mbostock)
- [](https://vida.io/explore)
- [](https://daranzolin.github.io/software/)
- [](https://cran.r-project.org/web/packages/scatterD3/vignettes/introduction.html)
D3 and leaflet
```{r, d31, eval=F}
# devtools::install_github("jcheng5/d3scatter")
require(pacman)
p_load(d3scatter,crosstalk,leaflet,tibble,httpuv)
# converting df to crosstalk df
sd <- SharedData$new(df)
sd$data()[,"var1"] # access data.frame
# load data
sd <- SharedData$new(quakes[sample(nrow(quakes), 100),])
# sd$data() %>% head
bscols(widths = c(12, 6, 6),
filter_slider("stations", "Stations", sd, ~stations),
leaflet(sd, width = "100%", height = 400) %>%
addTiles() %>%
addCircleMarkers(lng=sd$data()[,"long"],
lat=sd$data()[,"lat"],
stroke = F,
fill = T,
color = "red",
fillOpacity = 0.5,
radius = ~mag + 2,
label = ~paste0("Depth: ",as.character(depth))
),
d3scatter(sd, width = "100%", height = 400, ~mag, ~depth, color = ~stations)
)
```
Add dropdown menu to crosstalk
```{r, d31_}
bscols(widths = c(12, 6, 6),
filter_select(id = "stations",
label = "Stations",
sharedData = sd,
group = ~stations)
)
```
Convert R code to D3
https://rstudio.github.io/r2d3/articles/visualization_options.html
Create calendar plot
```{r, d32, eval=T}
# https://rstudio.github.io/r2d3/articles/gallery/calendar/ install.packages('r2d3')
require(r2d3)
require(readr)
require(dplyr)
require(colorspace);require(scales);require(stringr)
# col pal
col <- "PuBuGn" # seq
col2 <- "Tropic" # diverge
# seq
pal <- sequential_hcl(12, col)
# pal %>% show_col(borders = NA,labels=F)
paste0('"',pal,'"') %>% cat(sep=",")
# diverge
pal <- diverge_hcl(12, col2)
# pal %>% show_col(borders = NA,labels=F)
# paste0('"',pal,'"') %>% cat(sep=",")
cal <- read_csv("https://raw.githubusercontent.com/rstudio/r2d3/master/vignettes/gallery/calendar/dji-latest.csv")
r2d3(data = cal,
d3_version = 4,
container = "div",
options = list(start = 2006, end = 2011),
script = "calendar.js"
)
```
<!-- ![](img/d3_2.jpg) -->
Raindrop D3 animate chart
<!-- https://daranzolin.github.io/software/ -->
```{r, d33, eval = F}
# library(d3rain)
df %>%
d3rain(var_category, var_numeric,
toolTip = var_colour) %>%
drip_settings(dripSequence = 'iterate',
ease = 'bounce',
jitterWidth = 20,
dripSpeed = 1000,
dripFill = colpal) %>%
chart_settings(fontFamily = font,
yAxisTickLocation = 'left')
```
[rCharts](https://www.rpubs.com/dnchari/rcharts)
* Bubble
* Scatter
* + more
```{r, d34}
pacman::p_load(rCharts)
h4 = hPlot(Pulse ~ Height, data = MASS::survey, type = 'bubble', group = 'Sex', size = 'Age', radius = 6, group.na = "Not Available")
h4$chart(zoomType = "xy")
h4$exporting(enabled = F)
# h4$print(include_assets=T) # print d3js output
h4
```
![](img/d3_4.jpg)
### Data frames
Reversing order of rows in dataframe/entire df
```{r,d1}
# df = data.frame
require(tidyverse)
df %>% map_df(rev)
```
Visualise data structure as tree
```{r, d2, eval = T}
#explore package
require(DataExplorer)
require(palmerpenguins)
p <- penguins
plot_str(p)
```
Convert df row values to columns and lengthen df (ideal for tables/matrix inputs)
<!-- from olympics dataviz -->
```{r, d3}
# convert each distinct value in var2 into new column while maintaining var1
require(reshape2)
require(tidyr)
df %>% dcast(var1~var2, fill = 0) # fill NAs with 0
df %>% dcast(. ~ var1, fill = NA, drop = T) # convert rows to cols for one variable
df %>% dcast(. ~ factor(var1, levels = unique(var1)), fill = NA, drop = T) # retain row order when converting to cols
df %>%
melt() %>%
tidyr::uncount(value) # lengthen df by each row value
# transpose
df %>% t %>% data.frame
```
Create custom df from existing data
```{r, d4}
# no need to rename
latlon_data <- with(world.cities, data.frame( # //maps
"city" = name,"country" = country.etc,"lat" = lat,"lon" = long,"population" = pop)
)
```
Convert df rows to cols and rename
```{r, d5}
df %>% as_tibble(rownames = "row_names") %>% # convert cols to rows
rename("year" = 1,"percent" = 2) %>% na.omit()
```
Select df cols based on string
```{r, d6}
df %>% select(contains("Lat"))
df %>% select(starts_with("Lat"))
```
Rename df with pipe
```{r,d7}
df %>% # df of two cols
`colnames<-`(c("A","B"))
# rename directly with 'select'
df %>%
select(Lat, Lon, "Site" = `Site name`)
```
Split df into multiple dfs based on row value
```{r, d8}
# create new col with rownames to split by (can also below use for splitting by single row)
ss <- c(
rep("A",7),
rep("B",6),
rep("C",5)
)
df1 <- df %>%
mutate("Split" = ss)
df1 %>% split(df$Split) # split by each unique element in df$Split
```
### `dplyr` basics
```{r,dplyr1}
require(dplyr,gapminder)
pacman::p_load(gapminder)
# mutate
africa_ranked <- mutate(gapminder,
"African" = continent == "Africa",
"RankPop" = rank(desc(pop))
)
# summarise data into one line
gapminder %>%
summarise("MinYear" = min(year,na.rm = T),
"MaxYear" = max(year),
"CountryCount" = n_distinct(country),
"Counts" = n()
)
gapminder %>%
summarise(median(lifeExp))
# group by
# vari = response var
# var1-var3 = conditional vars that will be considered in grouping
df %>%
group_by(var1,var2,var3) %>%
summarise("total" = vari %>% sum)
# plot will be var1 (x) vari (y), fill/group (var2), facet (var3)
gapminder %>%
group_by(continent) %>%
summarise(median(lifeExp))
# group by continent and filter by year
gapminder %>%
group_by("Continent" = continent) %>%
filter(year == 1992) %>%
summarise(LifeExpect = median(lifeExp)) -> life_cont_1992
# rename specific cols
df %>%
rename(.cols = 2:5, # only rename these cols
"Country" = 2,
"Gold" = 3,
"Silver" = 4,
"Bronze" = 5)
# replace case when values based on numeric range
df %>%
mutate(var1 = case_when(
between(var2, 1, 5) ~ "A",
between(var2, 6, 10) ~ "B",
T ~ var1)
)
# classic case when
df %>%
mutate_at("var1",funs(
case_when(var1 == 1 ~ "alt1",
var1 == 2 ~ "alt2",
T ~ "alt3")))
# get distinct count per grouped var
df %>% group_by(var1) %>%
summarise(n = n_distinct(var2))
# count instances
df %>% group_by(var1) %>% count(var2)
```
Execute unfriendly pipe functions inline in pipes
```{r, dplyr2}
require(palmerpenguins)
require(dplyr)
p <- penguins
# %T>%
p %T>% glimpse %>% select(island)
# with()
p %>%
with(lm(body_mass_g ~ flipper_length_mm)) %>%
summary()
# %$%
# when var on lhs is undefined
require(magrittr)
data.frame(z = rnorm(100)) %$%
ts.plot(z)
```
Apply function easily using `mutate_at`
```{r, dplyr3}
# eg 1
df %>%
mutate_at("var1", ~str_replace_all(.," ","<br>"))
# eg 2
df %>%
mutate_at("layer", ~replace(.,is.nan(.), 0))
```
Expand/fill df by number of repeat instances
<!-- https://stackoverflow.com/questions/2894775/repeat-each-row-of-data-frame-the-number-of-times-specified-in-a-column -->
```{r, dplyr4}
require(tidyr)
df %>% select(v1,v2,v3) %>%
melt() %>%
tidyr::uncount(value) %>% # expand df by no. of instances (value from melted table)
select(variable,v1) # reorder for colpal
```
Arrange df col by custom order
```{r, dplyr5}
var_levels <- c("A","C","B") # custom order
# opt 1
df %>%
filter(var1 %in% var_levels) %>%
arrange(var1 = factor(var1,levels = var_levels))
# with mutate
df %>%
mutate("var1" = factor(var1, levels = var_levels)) %>%
arrange(var1)
# get top n value based on wt variable
# also works for sfc
df %>%
group_by(country) %>% # optional
top_n(n = 5, wt = area) # get top 5 geometries bassed on area
```
Remove unwanted df row using string arg
```{r, dplyr6}
df %>%
slice(-str_which(var1,"Unwanted point"))
```
Separate char values within df row into separate columns
```{r, dplyr7}
df %>%
tidyr::separate(col = "ColumnA",
into = c("lon", "lat", "elev"), sep = " ", remove = T) %>% # separate char into individual columns
mutate_all(as.numeric)
```
Get distinct values across multiple columns
```{r, dplyr8}
# distinct
df %>%
distinct(v1, v2, v3, .keep_all = T)
# non-distinct only
df %>%
group_by(v1, v2, v3) %>%
filter(n() > 1)
# exclude any non-distinct
df %>%
group_by(v1, v2, v3) %>%
filter(n() == 1)
# base method
df[!duplicated(df[1:3]),]
df[!duplicated(df[c("var1","var2"),]),]
```
Split one col into two separate cols and mutate (mutate and mutate_at in one line)
```{r, dplyr9}
df %>%
mutate(Year = var1 %>% str_split_fixed("-",Inf) %>% .[,1],
Month = var1 %>% str_split_fixed("-",Inf) %>% .[,2]) %>%
mutate_at(c("Year","Month"),as.numeric)
```
Apply multiple `mutate_at` functions
```{r, dplyr10}
# use list for multiple functions of either one or multiple cols
df %>% mutate_at(5:7, list(
~str_remove_all(., "string1|string2|"), # func1
~str_split_fixed(., "/", n = 2) # func2
))
# Apply multiple `mutate` functions using select or contains
df %>% select(contains("string1")) %>% # select var
mutate_all(~str_remove_all(., "string1|string2|") %>% as.numeric) # apply funcs
```
Mutate multiple vars
```{r, dplyr11, eval = F}
require(lubridate)
df %>%
mutate(AM = timevar %>% am,
Hour = timevar %>% hour,
Day = timevar %>% day,
Month = timevar %>% month,
Meridian = timevar %>%
round_date(unit = "hour") %>% # round off hour
format("%I") %>% as.numeric) # get 12 hour time
```
Seperate/detect df into categories based on row name
```{r, dplyr12}
df %>% filter(Restaurants %>% str_detect("Market|Water"))
```
Using `ifelse` with `mutate`
```{r,dplyr13}
df %>% mutate_at("var1", ~ifelse(. > 0.5, "this","that"))
```
Gather/melt data into groups/stacks
```{r,dplyr14}
df %>% gather(key = "Country", value = "value")
# reorder factors to df
```
Count instances of grouped data
```{r,dplyr15}
df %>%
group_by(date) %>%
tally(var1 * var2, name = "new_var1")
```
Lengthen df by column variables
(see https://haswal.github.io/pivot/ for good visual example)
```{r,dplyr16}
# select vars you want and lengthen by 'var_n'
# e.g. var_n = year
df %>%
tidyr::pivot_longer(cols = c(
var1, var2, var3
)) %>%
select(var_n, name, value)
# year name value
# <chr> <chr> <int>
# A var1 7
# A var2 4
# A var3 8
# B var1 3
# B var2 10
# B var3 2
# C var1 6
# C var2 1
# C var3 9
```
Separate/split df into individual dfs based on repeating value in a column
```{r,dplyr17}
# Name Description IDS geometry
# <fct> <fct> <fct> <GEOMETRY [°]>
# 1 2023 "" 0 LINESTRING Z (12.4822 41.89…
# 2 Rome "" 1 POINT Z (12.4822 41.8967 0)
# 3 Grosse… "" 2 POINT Z (11.11239 42.76355 …
# 4 San Gi… "" 3 POINT Z (11.04341 43.4672 0)
# 5 Floren… "" 0 POINT Z (11.25767 43.76997 …
# 6 Interl… "" 1 POINT Z (11.25767 43.76997 …
df %>%
mutate(trips = cumsum(IDS == 0)) %>% # create new helper col between every instance of 0 in IDS
group_by(trips) %>% # group by this helper col
group_split() %>% # spit into individual dfs
set_names(LETTERS[1:length(.)]) %>% # create new names for each df
imap(~write_csv(.x, paste0(.y, ".csv"))) # save each object '.x' as '.y' to dir as csv based on their list names
```
### Generic functions
Convert character class to numeric (ideal when creating colour palettes to turn string cols in df to numeric)
```{r, g1}
require(dplyr)
set.seed(12)
df <- data.frame("X"=LETTERS[sample(20)])
int_vec <- df$X %>% unlist %>% as.factor %>% as.integer # converts to numbers
int_vec ; df$I <- int_vec
df
```
Pipe vector to multiple arguments
```{r, g2}
require(dplyr)
# as list
Sys.time() %>% list(format(.,c(
"%y-%m",
"%Y-%m",
"%Y-%m")))
# use curly braces to keep original class
Sys.time() %>% {
format(.,c(
"%y-%m",
"%Y-%m",
"%Y-%m"))
}
```
Merge/combine/match/fill rows of two data frames based on value and retain original number of rows
```{r, g3}
merge(a, b, by = "ID", sort = F)
```
Access vars in df/tibble that failed to load eg. time series that return NA
```{r, g4}
# as tibble
df %>% attr("problems")
```
Search available methods for package
```{r, g5}
showMethods("coerce", classes = "sf")
methods(st_as_sf)
?methods
```
Get object size
```{r, g6}
df %>% object.size()
```
Assign multiple values to multiple LHS objects
```{r, g7}
require(zeallot)
values <- c(1, 2, 3, 4)
c(a, b) %<-% values[c(2, 4)] # assign `a` and `b`
c(a, b) %<-% c(1,"A") # returns both as char
```
Repeat vector n times (each)
```{r}
rep(c("A","B","C"), 10)
rep(c("A","B","C"), each = 10) # repeat each instance
```
Split vector into equal chunks
```{r}
ids <- 1:100
nn <- 20
split(ids,ceiling(seq_along(ids)/nn))
```
Find difference between vectors
```{r}
LETTERS[1:10] %>% setdiff(LETTERS[1:5])
```
Get order of vector
```{r}
df$id %>% order
```
### Google drive
Access files on Google Drive
Common commands: find, ls, mv, cp, mkdir, rm
http://googledrive.tidyverse.org/
```{r, eval=F}
require(googledrive)
drive_find(n_max=10) # set output limits
drive_find(type = "folder")
drive_get("~/Data/eli/feb.csv")
```
### HTML/XML
Write html code to dir
```{r}
code <- "<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>"
code <- paste(as.character(code), collapse = "\n")
write.table(code,
file="/Users/code.html",
quote = FALSE,
col.names = FALSE,
row.names = FALSE)
```
Extracting multiple nodes/range of nodes at once
```{r}
# require(dplyr,rvest,xml2,readr,magrittr)
url <- "https://www.postholer.com/databook/Appalachian-Trail/3"
url %>% read_html() %>% html_nodes("table") %>% .[1:3] # get range (node)
url %>% read_html() %>% html_nodes("table") %>% .[[1]] # get individual (nodeset)
```
Extract values within nested nodes
<!-- https://stackoverflow.com/questions/53198713/extracting-nested-xml-data-using-r-and-xml2-library -->
```{r}
require(purrr)
require(dplyr)
require(XML)
doc <- doc # gpx, xml, or XMLInternalDocument class
getNodeSet(doc,path = "//parentnode") %>%
purrr::map(xpathSApply,path = "child1/child2/child3", xmlValue) # extract values within child 3 node (three nodes deep) and separate into individual lists
# option 2
getNodeSet(gpx2,path = "//folder") %>%
lapply(function(x) {
list(
NODE1=x %>% xpathSApply(path = "placemark/track/coord", xmlValue)
)
}) %>% bind_rows()
```
Extract css class/id using `xpath`
```{r, html3}
require(rvest)
nid <- "\"class_large\"" # use css class (note quote escape)
url %>% read_html %>%
html_nodes(xpath = paste0('//*[@id=',nid,']'))
```
### Images
Recolor png/svg
```{r, img1}
require(magick)
png %>% image_colorize(color = "#EFEFEF", opacity = 70)
```
Read text from image
```{r, img2}
require(magick)
require(tesseract)
"test.png" %>%
image_read() %>%
image_ocr()
# return df with new word per col and associated bbox
"test.png" %>%