inSilecoMisc 0.4.0 (part 2/2)

April 21, 2020

  R package development inSilecoMisc

Kevin Cazelles

David Beauchesne

     

Table of Contents

In the first part of this post I introduced several functions available in the package inSilecoMisc. In this post, I keep on introducing features of the package you might find useful! If you did not read the first part of this post and are interested in reproducing the examples below, simply install inSilecoMisc:

1
2
3
# Run if package is not already installed
install.packages("remotes")
remotes::install_github("inSileco/inSilecoMisc")

Load it:

1
2
3
library("inSilecoMisc")
packageVersion("inSilecoMisc")
#R>  [1] '0.7.0.9000'

and you’re good to go!

scaleWithin()

I wrote scaleWithin() to handle color scales for a specific yet frequent situation. Let us say that I have 40 percentage values – meaning 0 to 100 – in a vector val

1
2
3
4
5
6
7
val <- runif(40, 0, 100)
val
#R>   [1] 48.356576 30.822254 84.135164 53.910783 59.037490 50.446329 31.751785 24.614490 68.198350
#R>  [10] 22.459452 28.476940 19.098101 72.231098  2.225541 23.542917 37.545987 27.691972 46.106000
#R>  [19] 90.463833 69.125617 90.382259 49.733769 32.202188 21.034731 41.327842 91.631972 95.546316
#R>  [28]  9.790313 77.513257 52.101588 96.956039 21.754604 21.504867 14.190760 15.168308 69.459561
#R>  [37] 41.347428 18.358585 74.521314 82.091143

and that I wish to create a color scale with 25 tones. I use showPalette() to show the color palette:

1
2
pal <- colorRampPalette(c("#f9fa98", "#500127"))(25)
graphicsutils::showPalette(pal)

But the color scale should be used for the range [30%-70%], meaning that values below 30% should have the lowest values and values above 70%, the highest one. The caption should thus indicate \(\geqslant\) 30% and \(\leqslant\) 70%. Then the function scaleWithin() is very handy!

1
2
3
4
scaleWithin(val, n = 25, mn = 30, mx = 70)
#R>   [1] 12  1 25 15 19 13  2  1 24  1  1  1 25  1  1  5  1 11 25 25 25 13  2  1  8 25 25  1 25 14 25  1
#R>  [33]  1  1  1 25  8  1 25 25
graphicsutils::showPalette(pal[scaleWithin(val, n = 25, mn = 30, mx = 70)], add_codecolor = FALSE)

Even though this function is pretty useful – at least I think it is! – I had a lot of trouble conveying why! So, in the last version of inSilecoMisc, I re-wrote the entire documentation and I hope that, together with this example, others will, as I so, find it useful.

Messages

Daily, I use R packages and R functions to analyze data, create model, run simulations, and a number of other things! So I write scripts that combine functions from various packages to create pipelines that do the analyses I need. When running such scripts, I like having information reported on a clear and visual way, that is why I value packages such as progress, crayon and cli. In inSilecoMisc, inspired by messages reported by devtools when building a package, I created four simple message functions using crayon and cli packages to standardize messages in my scripts.

1
2
3
# 1. msgInfo() indicates what the upcoming computation
msgInfo("this is what's gonna happen next")
#R>  ℹ this is what's gonna happen next
1
2
3
# 2. msgWarning() reminds me something important that should not affect the run
msgWarning("Got to be careful")
#R>  ⚠ Got to be careful
1
2
3
# 3. msgError() when something went wrong (and I anticipated that it could happen)
msgError("Something wrong")
#R>  ✖ Something wrong
1
2
3
# 4. msgSuccess() when a step/ a computation has been successfully completed
msgSuccess("All good")
#R>  ✔ All good

These functions help me structure my scripts. Here is a contrived example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
scr_min <- function() {
  # msgInfo() lets me know where I am in the script
  msgInfo("Average random values")
  set.seed(111)
  out <- mean(runif(100))
  msgSuccess("Done!")
  # msgSuccess() indicates the successful completion of this part
  out
}
scr_min()
#R>  ℹ Average random values
#R>  ✔ Done!
#R>  [1] 0.4895239

Another helpful aspect of these functions is that they all are based on message(). As such, if I want to execute a script quietly, all I need to do is to call suppressMessages() beforehand

1
2
3
# quiet run
suppressMessages(scr_min())
#R>  [1] 0.4895239

If you want to see an example of how I use these functions in a script for a scientific manuscript, check out the research compendium coocNotInteract.

tblDown()

Last but not least, I’d like to introduce a function to quickly write table data frame (or a list of data frames) in documents of various formats. I created tblDown() for a colleague of mine that was looking for a quick way to export a table. In the package knitr, there is the very handy function kable() that quickly writes a data frame in various formats.

1
knitr::kable(head(CO2))
Plant Type Treatment conc uptake
Qn1 Quebec nonchilled 95 16.0
Qn1 Quebec nonchilled 175 30.4
Qn1 Quebec nonchilled 250 34.8
Qn1 Quebec nonchilled 350 37.2
Qn1 Quebec nonchilled 500 35.3
Qn1 Quebec nonchilled 675 39.2

I wrote a function that calls kable() to write the data frame and then renders the table(s) in the desired format indicated by the extension of the output file (docx by default) using pandoc.

1
2
# NB tblDown(head(CO2)) returns table.docx by default
tblDown(head(CO2), output_file = "table.odt")
table_odt.png (screenshot)
table_odt.png (screenshot)

As I mentioned above tblDown() handles lists of data frames and the user can also provide a set of captions for every table and even separate them with section headers (of level 1).

1
2
3
tblDown(list(head(CO2), tail(CO2)), output_file = "tables.pdf",
  caption = c("This is the head of CO2", "This is the tail of CO2"),
  section = "Table")

Check out the output file ➡️ ! Note that in the example above I only use one character string for section and tblDown() has appended an index; this is also the default behavior for caption: if there are less captions or sections titles than data frames, vectors of captions (and/or sections) are repeated and an index is appended.

If you are already writing your documents with R Markdown, you may not need this. Yet keep in mind that tblDown() quickly exports tables in various formats with only one line of command!

That’s all folks 🎉!

Display information relative to the R session used to render this post.
 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
sessionInfo()
#R>  R version 4.4.2 (2024-10-31)
#R>  Platform: x86_64-pc-linux-gnu
#R>  Running under: Ubuntu 24.04.1 LTS
#R>  
#R>  Matrix products: default
#R>  BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#R>  LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
#R>  
#R>  locale:
#R>   [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8        LC_COLLATE=C.UTF-8    
#R>   [5] LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8    LC_PAPER=C.UTF-8       LC_NAME=C             
#R>   [9] LC_ADDRESS=C           LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   
#R>  
#R>  time zone: UTC
#R>  tzcode source: system (glibc)
#R>  
#R>  attached base packages:
#R>  [1] stats     graphics  grDevices utils     datasets  methods   base     
#R>  
#R>  other attached packages:
#R>  [1] inSilecoMisc_0.7.0.9000 inSilecoRef_0.1.1      
#R>  
#R>  loaded via a namespace (and not attached):
#R>   [1] sass_0.4.9               generics_0.1.3           xml2_1.3.6              
#R>   [4] blogdown_1.20            stringi_1.8.4            httpcode_0.3.0          
#R>   [7] graphicsutils_1.6.0.9000 digest_0.6.37            magrittr_2.0.3          
#R>  [10] evaluate_1.0.1           bookdown_0.42            fastmap_1.2.0           
#R>  [13] plyr_1.8.9               jsonlite_1.8.9           backports_1.5.0         
#R>  [16] crul_1.5.0               promises_1.3.2           bibtex_0.5.1            
#R>  [19] jquerylib_0.1.4          cli_3.6.3                shiny_1.10.0            
#R>  [22] crayon_1.5.3             rlang_1.1.4              cachem_1.1.0            
#R>  [25] yaml_2.3.10              tools_4.4.2              dplyr_1.1.4             
#R>  [28] httpuv_1.6.15            DT_0.33                  rcrossref_1.2.0         
#R>  [31] curl_6.1.0               vctrs_0.6.5              R6_2.5.1                
#R>  [34] mime_0.12                lifecycle_1.0.4          stringr_1.5.1           
#R>  [37] fs_1.6.5                 htmlwidgets_1.6.4        miniUI_0.1.1.1          
#R>  [40] pkgconfig_2.0.3          pillar_1.10.1            bslib_0.8.0             
#R>  [43] later_1.4.1              glue_1.8.0               Rcpp_1.0.13-1           
#R>  [46] xfun_0.50                tibble_3.2.1             tidyselect_1.2.1        
#R>  [49] knitr_1.49               xtable_1.8-4             htmltools_0.5.8.1       
#R>  [52] rmarkdown_2.29           compiler_4.4.2