-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathr.snippets
1368 lines (1170 loc) · 33.9 KB
/
r.snippets
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
# ============================================================================ #
#
# ---- Personal Snippets ----
#
# ============================================================================ #
# This document is all the snippets I may or may not use.
# Modify snippets: `usethis::edit_rstudio_snippets()`
# List of Snippets:
# General
# lib
# libr - recommended
# req
# src - source
# src2
# src_env
# src_env2
# ret
# ret_list
# ret_list2
# mat - matrix
# sg - setGeneric
# sm - setMethod
# sc - setClass
# shinyapp
# shinymod
# hh
# aa
# qq
# aq
# prettydate
# tts - time to string
# dateprnt
# mm
# a_eq
# shrtcut - create a shortcut
# quick_tip - create a tip
# maxima
# debug_mode
# para_proc - parallel processing
# bench_snip - benchmarking
#
# Control Flow:
# if - if
# el - else
# ei - else if
# ie - if else
# for
# while
# switch
# tryc - try catch
# TODO: tryc_r - try catch with restart
#
# Apply Family
# apply
# lapply
# sapply
# mapply
# tapply
# vapply
# rapply
#
# Standard Libraries
# tidyverse
# tidyverse2 - recommended using librarian
#
# Operators
# op_default
# zz
# op_notnull
# op_notnullish
#
# Section Headers
# comm_time - comment with time
# d_line - dashed line
# hdr_main
# hdr1
# hdr2
# hdr3
# hdr4
#
# ggplot2
# gg "ggplot generic"
# ggl "ggplot line"
# ggp "ggplot point"
# ggs "ggsave()"
# gge "geom_*"
# ggeb "element_blank"
# gger "element_rect"
# gget "element_text"
# ggel "element_line"
# ggt "themes"
# gg_cam
#
# dplyr, purrr:
# br "bind_rows()"
# bc "bind_cols()"
# jo "*_join"
# pm "purrr::map()"
# pmc "purrr::map_chr()"
# pmi "purrr::map_int()"
# pmb "purrr::map_lgl()"
# pmdb "purrr::map_dbl()"
# plonger
# pwider
# fun_map
# lam_fun
#
# Rmarkdown/Quarto
# r
# r2
# qmd_start
# save_loc_data
# dt
# auth
#
# Functions:
# fun
# lilbox
# fn_doc - use `docthis` to document a function
# fun_author
#
# Saving Shorcuts
# hfile - save a file with a header
# filen - file name skeleton, not used as much
# save_gg
# save_walk
# save_csv
# save_bin
#
# Opening Files, Folders, or Browser:
# open_path
# open_proj
# open_folder
# open_file
# open_edge
# open_chrome
# ------------------------------------------------------------
#
# General
#
# ------------------------------------------------------------
snippet lib
library("${1:package}")
# Dec 13, 2023
snippet libr
librarian::shelf(
quiet = TRUE,
librarian,
${1:package}
)
snippet req
require("${1:package}")
# ------------------------------------------------------------
# Shortcut: Sourcing Functions
# ------------------------------------------------------------
# below: `src2` is a better version
snippet src
source("${1:file.R}")
# updates the `src` snippet to source a file in the `scripts` folder
# update: Dec 13, 2023
# source script
snippet src2
source(here::here("scripts", "${1:file}.R"))
# allows sourcing scripts to an environment
snippet src_env
{
# attach functions to environment
${1:proj_functions} <- new.env()
source(here::here("scripts", "${2:file}.R"), local = ${1:proj_functions})
attach(${1:proj_functions})
rm(${1:proj_functions})
# functions available in `${1:proj_functions}` environment
cli::cli_alert_info(
c(
"These are custom functions avaiable for this project!\n",
"Documentations is location in {.path {here(\"scripts\")}}")
)
cli::cat_bullet(paste0(ls("${1:proj_functions}"), "()"))
}
# allows sourcing multiple scripts to an environment
snippet src_env2
{
# attach functions to environment
${1:proj_functions} <- new.env()
here::here("scripts", c("${2:file}.R")) |>
purrr::walk(~ source(.x, local = ${1:proj_functions}))
attach(${1:proj_functions})
rm(${1:proj_functions})
# functions available in `${1:proj_functions}` environment
cli::cli_alert_info(
c(
"These are custom functions avaiable for this project!\n",
"Documentations is location in {.path {here(\"scripts\")}}")
)
cli::cat_bullet(paste0(ls("${1:proj_functions}"), "()"))
}
snippet ret
return(${1:code})
# Dec 13, 2023
snippet ret_list
return(
list(
${1:var_name} = ${2:var}
)
)
# Dec 13, 2023
snippet ret_list2
${1:results} <-
list(
${2:var_name} = ${3:var}
)
return(${1:results})
snippet mat
matrix(${1:data}, nrow = ${2:rows}, ncol = ${3:cols})
snippet sg
setGeneric("${1:generic}", function(${2:x, ...}) {
standardGeneric("${1:generic}")
})
snippet sm
setMethod("${1:generic}", ${2:class}, function(${2:x, ...}) {
${0}
})
snippet sc
setClass("${1:Class}", slots = c(${2:name = "type"}))
snippet shinyapp
library(shiny)
ui <- fluidPage(
${0}
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
snippet shinymod
${1:name}_UI <- function(id) {
ns <- NS(id)
tagList(
${0}
)
}
${1:name} <- function(input, output, session) {
}
snippet hh
here::here("${1:path}")
snippet aa
${1:var} <- ${1:var} %>%
${0}
snippet qq
${1:var} %>%
${0}
snippet aq
${1:newvar} <- ${2:df} %>%
${0}
snippet prettydate
strftime(Sys.time(), "%A, %b %d, %Y")
snippet tts
strftime(Sys.time(), "${1:%F %T}")
snippet dateprnt
`r paste("# ${1:Author}", strftime(Sys.time(), "%A, %b %d, %Y"))`
# snippet a= # didnt work
snippet a_eq
${1:opt} = ${1:opt}
# ------------------------------------------------------------
# Shortcut: For new shortcuts
# ------------------------------------------------------------
# Nov 3, 2023
# shortcut to creating a new shortcut.
snippet shrtcut
# `r paste0(rep("-", 60), collapse = "")`
# Shortcut: ${1:shortcut purpose}
# `r paste0(rep("-", 60), collapse = "")`
# `r format(Sys.Date(), "%b %d, %Y")`
#
snippet ${2:shortcut_name}
${3:shortcut_code}
usethis::edit_rstudio_snippets() # delete after adding
# ------------------------------------------------------------
# Shortcut: Quick Tip
# ------------------------------------------------------------
# Nov 03, 2023
# snippet quick_tip
# # ============================================================================ #
# # ---- ${1:Name of Tip} ----
# # ============================================================================ #
# # `r format(Sys.Date(), "%b %d, %Y")`
# #
#
# # ============================================================================ #
# update: Dec 13, 2023
snippet quick_tip
# `r paste0(rep("=", 76), collapse = "")` #
# ---- ${1:Name of Tip} ----
# `r paste0(rep("=", 76), collapse = "")` #
# `r format(Sys.Date(), "%b %d, %Y")`
# `r paste0(rep("=", 76), collapse = "")` #
# ------------------------------------------------------------
# Shortcut: Maximima Program
# ------------------------------------------------------------
# Oct 2023
snippet maxima
```{maxima}`r ''`
L: sqrt(1 - 1/R^2);
assume(R > 0)$
'integrate(x, x, 0, L) = integrate(x, x, 0, L);
```
# ------------------------------------------------------------
# Shortcut: Set Debug Options
# ------------------------------------------------------------
# Dec 13, 2023
# This is useful when wanting to debug a function. Temporalily set the debug
# options to `recover` to stop when an error hits. Then, you can inspect the
# environment and see what is going on.
snippet debug_mode
{
options(error = recover)
# add code here
}
# ------------------------------------------------------------
# Shortcut: Debug One Time
# ------------------------------------------------------------
# Dec 19, 2023
#
snippet debug_1
debugonce(${1:fun})
# ------------------------------------------------------------
# Shortcut: Parallel Processing Template
# ------------------------------------------------------------
# Dec 14, 2023
#
snippet para_proc
# look for `furrr` and `progressr` package, and will skip is not downloaded.
parallel_pkgs <- c("furrr", "progressr", "future")
if (all(map_lgl(parallel_pkgs, ~ nzchar(system.file(package = .x))))) {
librarian::shelf(parallel_pkgs)
handlers("cli")
tictoc::tic() # <-- start clock
plan(multisession, workers = 5)
with_progress({
p <- progressor(steps = nrow(${1:data_frame}))
${1:data_frame} %>%
mutate(
# ${5:data_manipulation}
${2:new_var} = future_map(${3:col}, ~ ${4:func}, .progress = TRUE)
)
})
plan(sequential)
tictoc::toc() # <-- end clock
unshelf(parallel_pkgs)
} else {
cli_alert_warning(
c(
"The packages {.pkg {parallel_pkgs}} ",
"{col_red(\"were not found\")} in your search path.\n\n",
"If you want to do parallel processing, try:\n\n",
"\t{.code librarian::shelf({parallel_pkgs[1]}, {parallel_pkgs[2]})}"
)
)
}
rm(parallel_pkgs)
# ------------------------------------------------------------
# Shortcut: Benchmark
# ------------------------------------------------------------
# Dec 15, 2023
#
snippet bench_snip
bench <- microbenchmark::microbenchmark(
times = ${1:100},
control = list(order = "inorder"),
# check = "equal", # uncomment for equal
${2:one} = {
${3}
},
${4:two} = {
${5}
}
)
boxplot(bench)
# ------------------------------------------------------------
#
# Control Flow
#
# ------------------------------------------------------------
snippet if
if (${1:condition}) {
${0}
}
snippet el
else {
${0}
}
snippet ei
else if (${1:condition}) {
${0}
}
snippet ie
if (${1:cond}) {
${2:true}
} else {
${3:false}
}
snippet for
for (${1:variable} in ${2:vector}) {
${0}
}
snippet while
while (${1:condition}) {
${0}
}
snippet switch
switch(${1:object},
${2:case} = ${3:action}
)
snippet tryc
${1:variable} <-
tryCatch({
# main code
${2}
}, warning = function(w) {
# catch warning
message(sprintf("Warning in %s: %s", deparse(w[["call"]]), w[["message"]]))
${3}
}, error = function(e) {
# catch error
message(sprintf("Error in %s: %s", deparse(e[["call"]]), e[["message"]]))
${4}
}, finally = { # expression to be evaluated before returning or exiting
# end code to run after main code if no errors, remove if not needed
${5}
})
# ------------------------------------------------------------
# Shortcut: TODO: trycatch with restart
# ------------------------------------------------------------
# Dec 18, 2023
# add a snippet for a trycatch with restart
# snippet tryc_r
# ------------------------------------------------------------
#
# Apply Family
#
# ------------------------------------------------------------
snippet apply
apply(${1:array}, ${2:margin}, ${3:...})
snippet lapply
lapply(${1:list}, ${2:function})
snippet sapply
sapply(${1:list}, ${2:function})
snippet mapply
mapply(${1:function}, ${2:...})
snippet tapply
tapply(${1:vector}, ${2:index}, ${3:function})
snippet vapply
vapply(${1:list}, ${2:function}, FUN.VALUE = ${3:type}, ${4:...})
snippet rapply
rapply(${1:list}, ${2:function})
# ------------------------------------------------------------
#
# Standard Libraries
#
# ------------------------------------------------------------
# Snippets below inspired from https://github.com/gadenbuie/snippets
# updated with comment April 16, 2023
# - this snippet not used anymore in favor of `tidyvers2` with
# with `librarian` package
snippet tidyverse
library("ggplot2")
library("tibble")
library("tidyr")
library("readr")
library("purrr")
library("dplyr")
library("stringr")
library("forcats")
library("lubridate")
library("glue")
library("fs")
library("magrittr")
library("here")
# added Nov 26, 2022 by Sebastian Di Geronimo
# ---- updated Apil 16th, 2023
# - using if statement at top in case giving to someone else they will
# have less issues if they don't have `librarian`
# - also will help with downloading from github if they specify the
# user
# - changed because `conflicted` seems to work if included in `shelf()`
# - `conflicts_prefer()` adds multiple functions to the conflicted
snippet tidyverse2
if (!nzchar(system.file(package = "librarian")))
install.packages("librarian")
librarian::shelf(
quiet = TRUE,
librarian, conflicted, ggplot2, tibble, tidyr, readr, purrr, dplyr, stringr,
forcats, lubridate, glue, fs, magrittr, here,
# additional packages, if from GitHub, include username
)
conflicts_prefer(
dplyr::filter,
dplyr::select
)
# removed Apil 16th, 2023
# library("conflicted")
# conflict_prefer("filter", "dplyr")
# conflict_prefer("select", "dplyr")
# ------------------------------------------------------------
#
# Operators:
#
# ------------------------------------------------------------
#snippet op:default
snippet op_default
# use y if x is.null
`%||%` <- function(x, y) if (is.null(x)) y else x
snippet zz
${1:var} <- ${1:var} %||% ${0}
# snippet op:notnull
snippet op_notnull
# use y if x is not null (otherwise NULL)
`%??%` <- function(x, y) if (!is.null(x)) y
# snippet op:notnullish
snippet op_notnullish
# use y if x is not null(ish) (otherwise NULL)
`%??%` <- function(x, y) if (!is.null(x) && x != "") y
# ------------------------------------------------------------
# Shortcut: Matrix Multiplication
# ------------------------------------------------------------
snippet mm
%*%
# ------------------------------------------------------------
#
# Section Headers
#
# ------------------------------------------------------------
# comment time
# update: Dec 18, 2023
snippet comm_time
`r paste("#", date(), " ") |>
stringr::str_pad(width = 78, side = "right", pad = "-") |>
paste("#")`
# `r paste("#", date(), "------------------------------ # \n")`
# dashed line
# update: Dec 18, 2023
snippet d_line
`r paste("#", stringr::str_dup("-", times = 76), "#")`
# `r paste("# ------------------------------ # \n")`
# Sebastian D.
# Nov 12, 2022
# updated: Dec 13, 2023
snippet hdr_main
# `r paste0(rep("=", 76), collapse = "")` #
#
# ---- ${1:header} ----
#
# `r paste0(rep("=", 76), collapse = "")` #
# snippet hdr1
# # ============================================================================ #
# # ---- ${1:header} ----
# # ============================================================================ #
snippet hdr1
# `r paste0(rep("=", 76), collapse = "")` #
# ---- ${1:header} ----
# `r paste0(rep("=", 76), collapse = "")` #
snippet hdr2
# ---- ${1:header} ---- #
snippet hdr3
# ---- ${1:header}
snippet hdr4
# ---- ${1:header} ----
# ------------------------------------------------------------
#
# ggplot2
#
# ------------------------------------------------------------
snippet gg "ggplot generic"
ggplot(${1:data}, aes(${2:aes})) + ${0}
snippet ggl "ggplot line"
ggplot(${1:data}, aes(${2:x}, ${3:y})) +
geom_line()${0}
snippet ggp "ggplot point"
ggplot(${1:data}, aes(${2:x}, ${3:y})) +
geom_point()${0}
snippet ggs "ggsave()"
ggsave("${1:filename}.pdf", width = ${2:6}, height = ${3:6})${0}
snippet gge "geom_*"
geom_${1:point}(${0})
snippet ggeb "element_blank"
element_blank($0)
snippet gger "element_rect"
element_rect($0)
snippet gget "element_text"
element_text($0)
snippet ggel "element_line"
element_line($0)
# Dec 13, 2023
# ggthemes (default: calc)
snippet ggt "themes"
ggthemes::theme_${1:calc}(base_size = 12, base_family = "serif")
# ------------------------------------------------------------
# Shortcut: Add Camcorder When Testing Plots
# ------------------------------------------------------------
# Feb 15, 2024
# this will add code to use camcorder with typical values for saving. Once
# completed the adjustments, then save as normal using save_gg
snippet gg_cam
shelf(camcorder)
# camcorder::gg_record(
# dir = here::here("data", "cam_test", "${1:fig_name}"),
# device = "png",
# width = 90,
# height = 90 * 0.5625,
# dpi = 600,
# units = "mm"
# )
# shell.exec(here::here("data", "cam_test", "${1:fig_name}"))
# gg_stop_recording()
# ------------------------------------------------------------
#
# dplyr, purrr
#
# ------------------------------------------------------------
snippet br "bind_rows()"
bind_rows(${0})
snippet bc "bind_cols()"
bind_cols(${0})
snippet jo "*_join"
${1:inner}_join(${0})
# superseded: use map |> list_rbind
# removed: Dec 13, 2023
# snippet pmd "purrr::map_dfr()"
# purrr::map_dfr(${0})
#
# superseded: use map |> list_cbind
# snippet pmdc "purrr::map_dfc()"
# purrr::map_dfc(${0})
snippet pm "purrr::map()"
purrr::map(${0})
snippet pmc "purrr::map_chr()"
purrr::map_chr(${0})
snippet pmi "purrr::map_int()"
purrr::map_int(${0})
snippet pmb "purrr::map_lgl()"
purrr::map_lgl(${0})
snippet pmdb "purrr::map_dbl()"
purrr::map_dbl(${0})
# ------------------------------------------------------------
# Pivoting Shortcuts (August 23, 2022)
# ------------------------------------------------------------
# from https://www.infoworld.com/article/3637083/never-look-up-tidyrs-pivotwider-or-pivotlonger-again.html
#snippet plonger
# pivot_longer(${1:mydf},
# cols = ${2:columns to pivot long},
# names_to = "${3:desired name for category column}",
# values_to = "${4:desired name for value column}"
# )
#snippet pwider
# pivot_wider(${1:mydf},
# # id_cols = ${2:optional vector of unaffected columns},
# names_from = c(${3:category column(s) to pivot wide}),
# values_from = c(${4:value column(s) that hold data for each category column}),
# names_sep = "_"
# )
# update plonger (Janurary 30, 2023)
snippet plonger
pivot_longer(
data = .,
cols = c(), # columns to pivot long,
names_to = "name", # desired name for category column
values_to = "value", # desired name for value column
)
# update pwider (Feburary 02, 2023)
snippet pwider
pivot_wider(
data = .,
id_cols = c(), # *optional* vector of unaffected columns,
names_from = c(), # category column(s) to pivot wide
values_from = c(), # value column(s) that hold data for each category column
names_sep = "_",
names_repair = janitor::make_clean_names
)
# ------------------------------------------------------------
# Shortcut: Function Use within `map()` function
# ------------------------------------------------------------
# May 9, 2023
snippet fun_map
function(${1:input}) {
${2:}
}
# ------------------------------------------------------------
# Shortcut: Lambda Function
# ------------------------------------------------------------
# Mar 16, 2023
# update: Dec 13, 2023
# Anonymous functions using lambda notation instead of `function()` or `~`
# ex (\(x) x + 1)(3)
snippet lam_fun
\(${1:inputs}) {
${2:fun}
}
# ------------------------------------------------------------
#
# Rmarkdown/Quarto
#
# ------------------------------------------------------------
# note: not necessary anymore
snippet r
```{r ${1:label}, ${2:options}}
${0}
```
# not needed anymore
# separate two chunks
snippet r2
```
```{r ${1:label}}
# ------------------------------------------------------------
# Shortcut: Start `qmd_start` function (Oct 2023)
# ------------------------------------------------------------
# since creating a template qmd file is hard, this is the header code
# I want to use
# date: "`r Sys.Date()`"
# update Dec 17, 2023
snippet qmd_start
if (!nzchar(system.file(package = "librarian")))
install.packages("librarian")
librarian::shelf(
quiet = TRUE,
librarian, conflicted, ggplot2, tibble, tidyr, readr, purrr, dplyr, stringr,
forcats, lubridate, glue, fs, magrittr, here,
# additional
)
conflicts_prefer(
dplyr::filter(),
dplyr::select()
)
(function() {
context <- rstudioapi::getActiveDocumentContext()
lign <- min(grep("format", context\$contents))
lign <- 1
rstudioapi::modifyRange(
location = rstudioapi::document_range(
rstudioapi::document_position(lign, 1),
rstudioapi::document_position(lign, 77777)
),
#text = paste0("author: \"Sebastian Di Geronimo\"\ndate: \"", Sys.Date(), "\"\n"),
text =
paste0(
"---\n",
"title: \"${1:title}\"\n",
"author: \"Sebastian Di Geronimo\"\ndate: \"", Sys.Date(),
"\"\nformat: html",
"\neditor: source",
"\n---\n\n",
"# 1.0 ---- Summary of Document ----\n\n\n\n",
"# 2.0 ---- Setup ----\n\n\n",
"## 2.1 Load Libraries\n\n",
"```{r setup, include=FALSE}"),
id = context\$id
)
context <- rstudioapi::getActiveDocumentContext()
lign_start <- (grep("\\\(function\\\(\\\) \\\{", context\$contents))
lign_end <- (grep("\\\}\\\)\\\(\\\)", context\$contents))
rstudioapi::modifyRange(
location = rstudioapi::document_range(
rstudioapi::document_position(lign_start, 1),
rstudioapi::document_position(lign_end, 777777)
),
text = "",
id = context\$id
)
})()${2:}
```
## 2.2 Load Dataset
```{r load-data}
# run snippet after saving file
save_loc_data
# ------------------------------------------------------------
# Shortcut: Set Location and Save Data
# ------------------------------------------------------------
# Dec 15, 2023
# update: Dec 17, 2023
# - changed `stringr::str_remove("\\.qmd|\\.Rmd")`
# to `tools::file_path_sans_ext()`")`
snippet save_loc_data
# set location to save data and plots
dir_data_save <- here("data", "processed", "`r basename(rstudioapi::getActiveDocumentContext()$path) |>
tools::file_path_sans_ext()`")
dir_plt_save <- here("data", "plots", "`r basename(rstudioapi::getActiveDocumentContext()$path) |>
tools::file_path_sans_ext()`")
# ------------------------------------------------------------
# Shortcut: Print Date
# ------------------------------------------------------------
# Mar 22, 2023
# Used in qmd yaml header
# Not super useful now
snippet dt
date: "`r Sys.Date()`"
# ------------------------------------------------------------
# Shortcut: Add Author to YAML Header
# ------------------------------------------------------------
# Dec 18, 2023
# Will need to edit author name if different
snippet auth
(function() {
context <- rstudioapi::getActiveDocumentContext()
lign <- min(grep("format", context\$contents))
rstudioapi::modifyRange(
location = rstudioapi::document_range(
rstudioapi::document_position(lign, 1),
rstudioapi::document_position(lign, 1)
),
text = paste0("author: \"Sebastian Di Geronimo\"\ndate: \"", Sys.Date(), "\"\n"),
id = context\$id
)
context <- rstudioapi::getActiveDocumentContext()
lign_start <- min(grep("\\\(function\\\(\\\) \\\{", context\$contents))
lign_end <- min(grep("\\\}\\\)\\\(\\\)", context\$contents))
rstudioapi::modifyRange(
location = rstudioapi::document_range(
rstudioapi::document_position(lign_start, 1),
rstudioapi::document_position(lign_end, 777777)
),
text = "",
id = context\$id
)
})()
# ------------------------------------------------------------
#
# Functions
#
# ------------------------------------------------------------
# edit June 2, 2023 to include `end of function`
snippet fun
${1:name} <- function(${2:variables}) {
${0}
# ---- end of function ${1:name}
}
# ------------------------------------------------------------
# Shortcut: Function Box
# ------------------------------------------------------------
# Dec 17, 2023
# Create a box around a function name and document with the current variables
# This takes inspiration from:
# - https://github.com/VincentGuyader/littleboxes
# - https://github.com/mdlincoln/docthis/tree/master
#
# This is to help to use as a shortcut instead using the addin buttom