R

General

  • R summary from an university statistics course
    Such file is somewhere in https://rpubs.com/Topological_Parallax/
    The password is yoshi.

  • Resetea RStudio sin necesidad de cerrarlo
    En la consola, escribe lo siguiente:
    .rs.restartR()

  • Revertir el orden de una lista de datos
    rev(datos)

  • "Vector de vectores"
    No puedes usar algo como c(c(1,2),c(3,4)).
    Contrario a Python, donde puedes definir un array que contiene arrays, para definir un "vector de vectores" en R, se crea una lista ( list( )) cuyos elementos son vectores c( ). Pero, para acceder a los elementos de dicha lista, requieres emplear doble corchete.
    Ejemplo:

    lista <- list(c(1,2),c(3,4))
    # lista[[1]] vale c(1,2) y se tiene lista[[1]][1] = 1, 
    # pero con lista[1] no hay manera simple de acceder a los elementos de lista[[1]]. 
  • Revisar si cierto valor está en un vector
    Ejemplo:

    vector <- c(1,2,3)
    sum(vector %in% 1) # Vale 0 si y solo si el valor 1 no está en "vector".
  • Remueve uno o más elementos de un vector
    Ejemplo:

    vector <- c(1,2,3,4)
    vector <- vector[!vector %in% c(1,4)] 
    # Entonces ahora "vector" vale c(2,3)
  • Length of a string
    nchar(some_string) outputs its number of characters.
    More information: https://stackoverflow.com/questions/11134812/how-to-find-the-length-of-a-string-in-r

  • Select certain items from a matrix
    Great method: https://stackoverflow.com/questions/11993810/selecting-specific-elements-from-a-matrix-all-at-once

  • Print while staying on the same text/code line (no line break)
    Use ca(...) instead of print(...).

  • Convert R vector into one R string
    new_string <- paste(some_vector,collapse=" ")

  • Insert multiple code commands inside one line
    Example: x <- 1; y <- 2; x+y

  • Global variable
    https://www.w3schools.com/r/r_variables_global.asp

  • RStudio snippets
    You can modify RStudio’s snippets via
    Tools -> Global Options … -> Code -> Edit Snippets…

    Alternatively, for example, you can modify the snippets for markdown files via   usethis::edit_rstudio_snippets("markdown") .

    When using R Markdown, the snippets have to be activated inside the Rmd document via writing the snippet name and then pressing Ctrl+Shift.

  • Convert categorical values into numeric ones
    Example:

    categorical <- c('hombre','mujer')  
    numerical <- unclass(factor(x))
  • Conditionally install a R package if it has not been installed
    Whenever sharing a R file to someone, perhaps some function does not work properly in their computer, due to a missing R package.
    The following code checks if a package is already installed on the user’s PC and installs it in case it wasn’t already:

    # Example with the 'haven' R package
    if (!require('haven')) install.packages('haven')
    library(haven)

R Markdown

  • Some of the potential of Rmarkdown
    Rmarkdown’s god expo

  • Texto en cursiva
    _italic_ = italic

  • Texto en negrita
    ** bold ** = bold

  • Texto en cursiva y negrita
    *** texto *** = texto

  • Link

    [hyperlink](url)
  • Imagen

    ![nombre_imagen](url o dirección en carpeta)
  • Footnote

    text^[footnote]
  • Add a comment inside a rmd file
    Use <!-- commented code -->.
    In Windows, press Ctrl+Shit+C after highlighting in RStudio the code you wish to comment out, and it will do so. The same command can also uncomment code.

  • Leave blank space inside .md output text

    &nbsp;
  • Line break
    Use \ at the end of a line to set a new line, or end the line with two spaces, or use <br/>, which works for most document outputs, instead of \.
    Example:
    Fist \
    Second

  • Add extra space after a line break
    \ (alone in a line) (you can use more than one of these after the other (separate lines of course) )
    As an analogue tool to \vspace{Xem} from LaTeX, I suggest using
    <p style="margin-bottom: 10px;"> &nbsp; </p>
    in order to alter the desired space to leave blank.

  • Horizontal table
    You can do it using HTML, for example:

    <table>
      <tr>
        <th>Row 1</th>
          <td>Item 1 of row 1</td>
          <td>Item 2 of row 1</td>
        </tr>
        <tr>
          <th>Row 2</th>
          <td>Item 1 of row 2</td>
          <td>Item 2 of row 2</td>
        </tr>
    </table>
  • Good enough way to include a video

    [![ ](thumbnail_link)](video_link)
  • Centrar imagen
    Ejemplo:

    <img src = "test.jpg" alt = "fractal" width = "50%">

    css chunk:

    img{ 
      display: block; 
        margin-left: auto; 
        margin-right: auto; 
    } 
  • More general way to center a part of the Rmd document

    <center>
      ... code
      ... chunk
      ... image
      etc
    </center>
  • Posicionar imagen
    Ejemplo:

    <img src = "test.jpg" alt = "fractal" width = "50%">

    css chunk:

    img{ 
      position: relative; 
        left: 50px;
    } 

    # Aquel comando left: 50 px añade un espacio en blanco de 50 píxeles
    a la izquierda de la imagen. También puedes emplear right: 100 px para
    añadir un espacio en blanco de 100 píxeles a la derecha de la imagen.

  • Background color
    Ejemplo:

    body {
      background-color: #BBDDEE;
    }
  • HTML theme options
    Some examples are included in here.

  • Set HTML language via the YAML
    Example:

    ---
    lang: "en"
    output: html_document
    ---
  • Include python code
    Add the following in the default “setup” chunk:

    library(reticulate)
    knitr::knit_engines$set(python.reticulate = reticulate::eng_python)

    Then, to use python inside an rmd file, use:

    ```{python}
    # your code goes here
    ```
  • Include audio using HTML
    Example:
    HTML code:

    <audio controls>
      <source src = "Jazz_Intro.mp3" type = "audio/mpeg">
    </audio>
  • Include video using HTML
    Example:
    HTML code:

    <video width = 100% controls>
      <source src = "acorde_0.mp4" type = "video/mp4">
    </video>
  • Show plain text
    ```text
    blah blah blah
    ```
    You can avoid writing "text" after ``` and it still works.

  • Chunk highlighting  
    Say you want to show some code without it actually being executed. You could use the option eval=FALSE in the appropiate chunk, but there is a simpler way. HTML code example:
    ```html
    arbitrary html code that will not be executed
    ```

  • Some special characters
    In order to use certain characters in Rmarkdown, the syntax changes as follows:

    \ as \\
    ` as \`
    # as \#
    - as \-
    _ as \_
    * as \*
    " as \"
  • Alternative subtitle syntax
    Writing the subtitles this way allows us more configuration options using CSS, for example, via using “id”s.

    # title as <h1 id = "whatever"> title </h1>
    ## subtitle as <h2 id = "whatever"> subtitle </h2>
  • Highlight code
    `texto` = texto
    Works great when you need to insert inline code and avoid the problems of having to modify the special characters due to Rmarkdown’s rules. It can be customized via CSS, for example:

    Include the following in a CSS chunk:
    code { background: #000000; color: #FFFFFF; }
  • Semi automatic reporting
    If you create a rmd file using parameters in the YAML section, for example:

    params:
      day: 23

    Then, you can apply such parameters in the rmd file’s content via: ` r params$day ` , but with no space between right after and right before the respective ` symbols. Sometimes it does not work, so use params$day instead, and it will probably run smoothly now.

    That way, you can write such parameters in your rmd report and simply change the parameter values in the YAML section when you want to update the report. A faster way to do that is to click in the Knit section in RStudio, where there is a little downward, and click Knit with Parameters .... Doing that may require installing the Shiny package.

  • Automatize the date in the YAML section
    You can use the R command Sys.time() to get the current date, but the order presented differs from the usual way to show dates, so, I recommend including doing something like this in the YAML section:
    date: " ` r format(Sys.time(),'%d / %m / %Y') ` "
    , but with no space between right after and right before the respective ` symbols.

  • Split the text into columns
    More info: https://bookdown.org/yihui/rmarkdown-cookbook/multi-column.html Examples:

    :::::: {.columns}
    ::: {.column}
    texto 1
    :::
    
    ::: {.column}
    texto 2
    :::
    ::::::
    :::: {style="display: flex;"}
    
    ::: {style="width: 33%;"}
    Here is the **first** Div.
    
    \`\`\`r
    str(iris)
    \`\`\`
    :::
    
    ::: {style="width: 33%;"}
    And this block will be put on the right:
    
    \`\`\`r
    plot(iris[, -5])
    \`\`\`
    :::
    
    ::: {style="width: 33%;"}
    
    \`\`\`r
    head(cars)
    \`\`\`
    
    :::
    
    ::::
    
    
    ::::{style="display: flex;"}
    
    ::: {style="width: 33.33%;"}
    content ...
    :::
    
    ::: {style="width: 33.33%;"}
    content ...
    :::
    
    ::: {style="width: 33.33%;"}
    content ...
    :::
    
    ::::
  • Include text chunk and customize it
    Instead of simply writing
    ```
    blah blah blah
    ```
    , write
    ``` text
    blah blah blah
    ```
    That way the content of such text chunks can be customized via altering the CSS class text.
    Example:

    Include the following in a CSS chunk:
    .text { visibility: hidden; }
  • Faster work with HTML
    Given that knitting a document usually takes a while, you can set the YAML output as html_notebook, that way you don’t have to knit the document more than once, because it suffices to save the document (Ctrl+S) in RStudio and in the Viewer section it will update much faster than if you were to knit the document once more.

  • Style the table of contents
    I suggest this guide.
    CSS code for the table of contents of a previous version of this site:

    /* Table of contents */
    .tocify {border: none;}    
    .tocify .tocify-header {
      color: white;
      border-radius: 20px;
      margin: 25px;
    }
    .tocify .tocify-item {
      background: black;
      border-radius: 20px;
    }
    [data-tag="2"] > li {
      border-top: 2px solid white;
    }
    [data-unique="_Rmarkdown_"].active {
      color: #D83636 !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_Bookdown_"].active {
      color: #FFDFBD !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_Blogdown_"].active {
      color: #F0BD30 !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_Shiny_"].active {
      color: #5899DE !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_HTML_"].active {
      color: #FA7720 !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_CSS_"].active {
      color: #327FE5 !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_LaTeX_"].active {
      color: #000000 !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_Git_"].active {
      color: #f34f29 !important;
      background: white !important;
      font-size: 20px; 
    }
    [data-unique="_Python_"].active {
      color: #4B8BBE !important;
      background: white !important;
      font-size: 20px; 
    }
  • Style the tabsets
    As an example, this is the relevant CSS code for the tabsets on this file:

    .rmd > h1       {color: #D83636;}
    li > a[href="#rmd"]      {color: #D83636 !important;}
    li > a[href="#bookdown"] {color: #FFDFBD !important;}
    li > a[href="#blogdown"] {color: #F0BD30 !important;}
    li > a[href="#shiny"]    {color: #5899DE !important;}
    
    li > a[href="#html"]     {color: #FA7720 !important;}
    li > a[href="#css"]      {color: #327FE5 !important;}
    li > a[href="#js"]       {color: #F0DB4F !important;}
    
    #latex > h1     {color: #000000 !important;}
    
    #git > h1       {color: #f34f29 !important;}
    
    #python > h1    {color: #4B8BBE !important;}
    
    ul[role="tablist"] {
      background-color: black !important;
      border-radius: 20px;
    }
    
    /* Tabs */
    .nav-tabs > li > a.active, .nav-tabs > li > a:hover {
      color: black !important;
      background-color: white !important;
    }
    .nav-tabs > li > a:hover {
      cursor: default;
      border: 1px solid white;
    }
    
    }
  • Include external CSS urls into Rmarkdown
    Example using Bootstrap:

    ---
    title: "Bootstrap"
    output: html_document
    ---
    
    <style type="text/css">
    @import url("https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css");
    </style>
    
    <div class="alert alert-primary" role="alert">
      A simple primary alert—check it out!
    </div>
  • Include HTML file into a R Markdown document
    Inside a R chunk with echo=FALSE insert htmltools::includeHTML("my_HTML_file.html").

  • PDF output
    Sometimes knitting does not work properly when you change the Rmarkdown output from html_document to pdf_document, due to something in your code. A better way to transform HTML documents into pdf ones is via the package pagedown.
    Install it in RStudio with remotes::install_github('rstudio/pagedown'), then change the working directory with setwd('directory') to where your HTML file is located and finally use pagedown::chrome_print('file-name.html').
    The pagedown package it’s still a work in progress, so it’s not like LaTeX will soon be a thing of the past, but Yihui’s work is looking quite promising .

  • Display the ``` chunk symbols inside a chunk
    A problem arises when one tries to use the ` symbols inside a text chunk. Supposedly, there is a workaround using four ` symbols, instead of three, but it did not work for me, so I use the following:
    Example:
    Say I want to include inside a text chunk a R chunk that prints “Hello, world!”, then, instead of using the text chunk, I’d type:

    ```{r comment=NA}
    print("Hello, world!")
    ```

    And it will be displayed similar as if it had been a text chunk all along.

  • Include variables in HTML and CSS
    Example:

    ```{r}
    test <- -20
    rojo <- '#FF0000'
    azul <- "#0000FF"
    ```
    
    Hola
    
    <p style="margin-bottom: -20px;"> &nbsp; </p>
    
    <p style="color: `r rojo`;"> Hola </p>
    
    <p style="margin-bottom: `r test`px;"> &nbsp; </p>
    
    <p style="color: `r azul`;"> Hola </p>
  • Underline portion of a text
    Despite being able to underline HTML text using CSS, you can also use   \underline{\text{...}} so that only some words of the sentence are underlined, even if the Rmd output is a HTML document.

  • Non trivially display a data frame
    Example:

    knitr::kable(data_frame,align=rep('c', 9))
    # The align argument is unnecesary, but it will align the 9 columns
    # of the data_frame as "center".
  • Use conditional chunks
    If you wish for some chunk to be executed only if certain conditions are met, you may use logical values to do so.
    Example:

    ---
    title: "testing"
    output: html_document
    params:
        boolean: TRUE
    ---
    
    ```{r}
    verdura <- !FALSE  # aka TRUE
    ```
    
    ```{r eval=params$boolean}
    print("Hello, world!")
    ```
    
    ```{r eval=!params$boolean}
    print("Hola, mundo!")
    ```
    
    ```{css eval=verdura}
    body { text-align: center;}
    ```
    
    ```{js, eval=params$boolean}
    $('.title').css('color', 'red')
    ```

    Important: The variable next to eval= in the chunk must be logical, not a string, or it may not work. Therefore, use TRUE instead of "TRUE", and such.

  • Insert links directly
    Instead of using, for example, [https://www.google.com/](https://www.google.com/), write <https://www.google.com/>, because it achieves the same function.

  • Basic chunk compilation options

    • By defect, every command is compiled and the outputs appears in separate blocks.

    • collapse=TRUE: The code is compiled and the outputs appear in just one block.

    • echo=FALSE: The code is compiled, but only the outputs appear.

    • include=FALSE: The code is compiled, but no code nor outputs are shown.

    • eval=FALSE: The code appears but it’s not compiled. No outputs shown.

  • Create tabsets
    Example:

    ## Ejemplo de pestañas {.tabset}
    
    ### Pestaña 1
    
    content ...
    
    ### Pestaña 2
    
    content ...
    
    ## {-}

    For more properties, you could have used:

    ## Resultados semestrales {.tabset .tabset-fade .tabset-pills}

    Note that the empty heading, ## {-} could have been replaced by ## {.unnumbered}.

    Other method:

    ```{ r }
    xaringanExtra::use_panelset()
    xaringanExtra::style_panelset_tabs(font_family = "inherit")

    Panels in R Markdown!

    Tab One

    content…

    Tab Two

    Sub heading one

    content…

    Tab Three

    content…

    ``` This last method is much more general, also available in Xaringan.
    For more info, visit https://pkg.garrickadenbuie.com/xaringanExtra/#/panelset.

  • Style headers
    Example:

    ## Header 1 {.some_class}
    
    ...
    
    ## Header 2 {#some_id}

    That way, such headers wll inherit the properties you define elsewhere using CSS for such class and such id.

    • Do not include a certain header in the table of contents
      Example:
    # Some header {.unlisted}
  • Convert a R string into content of an Rmd file
    Short guide: https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html
    It allows for automatization of certain code creation, for example, CSS and Javascript. It does not seem to work for creating CSS or JS via chunks, but it does if you use <style> and <script> instead, thanks to the cat function and the chunk parameter results="asis" .
    Example:

    # Inside some R chunk, you'd have the following:
    
    library(stringr)
    neck <- function(matriz,bajo) {
      m <- nrow(matriz)
      n <- ncol(matriz)
    
      # Unique identifier
      semi_id <- as.vector(t(matriz))
      id <- ""
      for(i in semi_id){
        id <- paste(id,i,sep="")
      }
      id <- str_replace_all(string=id, pattern=" ", repl="")
      id <- str_replace_all(string=id, pattern="&nbsp;", repl="y")
    
      # HTML Table
      tabla <- paste("<table class=\"guitar ",id,"\">\n",sep="")
      for(i in 1:m){
        tabla <- paste(tabla,"  <tr>\n")
        for(j in 1:n){
          tabla <- paste(tabla,"    <td>",matriz[i,j],"</td>\n",sep="")
        }
        tabla <- paste(tabla,"  </tr>\n")
      }
      tabla <- paste(tabla,"</table>\n\n",sep="")
    
      # Styling
      estilo <- "<style>\n[class=\""
      estilo <- paste(estilo,id,"\"] > td {\n","  width: ",sep="")
      estilo <- paste(estilo,as.character(round(100/n,2)),"%;\n",sep="")
      estilo <- paste(estilo,"}\n</style>\n",sep="")
    
      # Obtain note positions
      posiciones <- list()
      counter <- 0
      for(i in 1:m){
        for(j in 1:n){
          if(nchar(matriz[i,j])<2){
            counter <- counter + 1
            posiciones[[counter]] <- c(i,j)
          }
        }
      }
      fret <- matrix(0,m,n)
      for(i in m:1){
        t <- 1 + 4*(m-i)
        fret[i,] <- t:(t+n-1)
      }
      filas <- NULL
      columnas <- NULL
      for(i in 1:length(posiciones)){
        filas[i] <- posiciones[[i]][1]
        columnas[i] <- posiciones[[i]][2]
      }
      call <- cbind(filas,columnas)
      indices <- rev(fret[call])
    
      # Adjusting the notes to be played
      k <- length(indices)
      indices <- indices - rep(indices[1]-1,k)
      if(bajo==-1){
        indices <- indices + rep(4*(6-m),k)  
      } else {
        indices <- indices + rep(bajo,k)
      }
    
      # Sound 
      notes <- c("D3","Eb3","E3","F3",
                "Gb3","G3","Ab3","A3",
                "Bb3","B3","C4","Db4",
                "D4","Eb4","E4","F4",
                "Gb4","G4","Ab4","A4",
                "Bb4","B4","C5","Db4","D5")
    
      sonido <- "\n"
      for(i in indices){
        sonido <- paste(sonido,"<audio class=\"","acorde",id,"\" preload=\"auto\">\n",sep="")
        sonido <- paste(sonido,"  <source src=\"audio/",notes[i],".mp3\"></source>\n",sep="")
        sonido <- paste(sonido,"</audio>\n\n",sep="")
      }
    
      # Javascript
      sonido <- paste(sonido,"<script>\n",sep="")
      sonido <- paste(sonido,"  var beep",id," = $(\".","acorde",id,"\");\n",sep="")
      sonido <- paste(sonido,"  $(\".",id,"\")\n",sep="")
      sonido <- paste(sonido,".mouseover(function() {\n",sep="")
    
      number_of_strings <- sum(!chord %in% "&nbsp; &nbsp;")
      for(i in 0:(number_of_strings-1)){
        sonido <- paste(sonido,"  beep",id,"[",as.character(i),"].play();\n",sep="")
        #sonido <- paste(sonido,"  setTimeout(function() {\n",sep="")
        #sonido <- paste(sonido,"    beepOne[",as.character(i),"].play();\n",sep="")
        #sonido <- paste(sonido,"  }, (3*1000));\n",sep="")
      }
    
      sonido <- paste(sonido,"});\n",sep="")
      sonido <- paste(sonido,"</script>\n",sep="")
    
      # guitar_diagram
      guitar_diagram <- paste(tabla,estilo,sonido,sep="")
      cat(guitar_diagram)
    
      # Chord notes
      cat(paste("<p style=\"text-align: center; margin-top: 10px;\">","Notes of the chord: ",sep=""))
      cat(notes[indices],sep="&nbsp; ")
      cat("</p>\n")
    
    # Now, to automatically generate the HTML, CSS and Javascript code from that function neck(.,.),
    # you'd need "neck(some_matrix,some_bajo_value)" inside another R chunk with parameter
    # results = "asis", which sort of means "print as it is".
  • Use R variable inside non R chunks
    Say you have some R variable named derivative and wish to use it inside a Python chunk. Then, simply use r.derivate inside that chunk as if it were a python variable and done.

  • R package for simple styling of xaringan presentations
    https://pkg.garrickadenbuie.com/xaringanthemer/

  • Export R data drame and save as a png file
    Example:
    kable(some_data_frame) %>% kable_styling %>% save_kable("some_data_frame.png")

  • Some nice scientific article templates

    ---
    title: "Astrology?"
    output:
      distill::distill_article:
        toc: true
    ---
  • Rotate, trim, add efects to image, etc
    The magick R package allows for simpler customization tools for images, rather than trying to do it via CSS.

  • Use R chunks via external R scripts
    Example:

  • Conditionally read Rmd file and insert into another Rmd
    Example:

     

  • Automatically render multiple versions of a Rmd file
    Example:

  • Set a global item counter
    If you use 1. for numbering items, R Markdown automatically numbers them appropriately, but such numbering will be reset in different sections, such as distinct # some title environments. Solution

  • Include conditional R code into the Rmd file
    Example:

    ```{r results = 'asis'}
    for (i in 1:3) {
      cat(
         '# section',
         i,
         '\n'
      )
      plot(cars[[1]][1:(10*i)],cars[[2]][1:(10*i)])
      cat('\n\n')
    }
    ```
  • Set properties to chunk
    Example:

    ```{r, out.width='25%', fig.align='center', fig.cap='Una legenda'}
    plot(cars)
    ```
  • Highlight code in displayed chunk code
    In the YAML section, you can set different options of highlighting the code from chunks displayed on the output file.   Example:

    ---
    title: test
    output: 
      html_document:
        highlight: tango
    ---

    Visuals of some of the different highlight options: https://www.garrickadenbuie.com/blog/pandoc-syntax-highlighting-examples/.

Bookdown

  • Short guide
    https://bookdown.org/yihui/rmarkdown-cookbook/bookdown.html

  • Create a book
    If you have RStudio, the easiest way to start a bookdown project is to select
    File -> New Project -> New Directory -> Book Project using bookdown after installing the bookdown library.

  • Remove the automatic numbering of chapters and sections
    In the _output.yml file of your book, insert number_sections: FALSE as an item of the bookdown::gitbook: part.

  • Remove the automatic naming of chapters
    In the _bookdown.yml file, simply change the chapter_name part to " ".

  • Render the book
    Once inside the bookdown project, execute bookdown::render_book('index.Rmd').
    Such method does not produce the pdf and epub output versions of the book, at least in the bookdown demo files I’ve worked with; however, the command rmarkdown::render_site(encoding = 'UTF-8') does, but, the rendering takes longer and the HTML output document is styled quite differently than with the bookdown command.

Blogdown

  • Update website created with Blogdown and Github
    En la consola de RStudio ejecuta blogdown::hugo_build().
    cd C:\my-website
    git add .
    git commit -a -m “Actualizando archivos”
    git push
    # It can take a couple minutes for the changes to be applied to the online page.

  • Change a que no haga knit tras every save
    En un archivo .Rprofile contenido en la carpeta general del website se puede cambiar esa opción.

  • Solve common Latex problem con el web theme del tutorial to create a site
    Change the params.toml file from math = false to math = true.
    Changing the comfig.toml math argument only impacted the actual post content, not the summary.

  • Directorio para cambiar el logo de la web page del hugo_academic theme
    \my-website\themes\github.com\wowchemy\wowchemy-hugo-modules\wowchemy\assets\media
    # Debes cambiar el archivo "icons.png"

  • Preview website
    blogdown::serve_site()

  • Check for possible errors
    blogdown::check_site()

  • Carpeta content
    That’s the directory where the source files for posts and pages are added.

  • addins
    Very useful commands on top side of RStudio.

Shiny

Shiny can work both in plain R and in R Markdown, but the overall structure of the code changes a little bit.

  • Insert Shiny code in Rmarkdown
    In the YAML section, add runtime: shiny. Works when the output file is html_document or ioslides_presentation. The library “shiny” must be included in the R code.

  • Shiny inputs in Rmarkdown
    You could insert one Shiny input command inside one R chunk (when I try to naively include more than one, it doesn’t work).
    For example:

    sliderInput(
                inputId="chord_size",label="Chord size", 
                min = 2, max = 6, value=3
    )

    Or, you could include more than one Shiny input command inside one R chunk via something like:

    library(shiny)
    mainPanel(
        sliderInput(
                    inputId="chord_size",label="Chord size", 
                    min = 2, max = 6, value=3
                    ),
        sliderInput(
                    inputId="rotation",label="Angle of rotation (in degrees)",
                    min = 1, max = 180, value=180, step = 1
                    )
    )
  • Styling Shiny buttons in Rmarkdown
    Using HTML, you can include a Shiny input command in a R chunk like this in order to style it more easily:

    library(shiny)
    mainPanel(
        div(id="chord_size",style="display: inline-block; width: 300px;",
          sliderInput(
                      inputId="chord_size",label="Chord size", 
                      min = 2, max = 6, value=3
                      )),
        br(),br(),
        div(id="rotation",style="display: inline-block; width: 300px;",
            sliderInput(
                        inputId="rotation",label="Angle of rotation (in degrees)",
                        min = 1, max = 180, value=180, step = 1
                        ))

    The command br() is to set a line break.
    That way, you can edit Shiny inputs with CSS via their id.

  • Delay Shiny input in Rmarkdown
    Sometimes one requires that, after receiving an input via the user, the program waits a litte bit of time before doing something with that input, maybe print it or whatever. Here is an example of how to delay the program after receiving the input, which in this case is labelled as rotation and would have already been defined previously in the respective Rmarkdown document:
    R chunk:

    library(shiny)
    v <- reactiveValues()
    observe({ v$r <- debounce(function(){input$rotation},750) })  # wait 750 milliseconds after receiving the input rotation
    renderPlotly({
      if(input$chord_size < 5 && input$even_1 == 0 && input$even_2 == 0){
      music_graph(input$chord_size,v$r(),0,0)
      }
    })
  • Display customizable message in case of some error
    Example:

    library(shiny)
    renderUI({
        validate(
                need(input$argument_1 == 0, "Error: For chord size smaller than 5, the penultimate argument must be zero."),
                need(input$argument_1 < input$argument_2,"Error: For chord size 6, the last argument must be greater than the penultimate argument.")
                )
    })
    # The validate function can also be inside renderPlotly({ ... }) .
  • Styling of error messages
    Example to style the usual error message I’ve found using Shiny in Rmarkdown:
    CSS chunk:

    shiny-output-error:before {visibility: hidden;}
    .shiny-output-error {visibility: hidden;}
    .shiny-output-error-validation {
      visibility: visible;
        color: #FF6A6A; 
        font-weight: bold;
    }

    The class shiny-output-error-validation is for the messages I’ve got when using the validate function, but, if it doesn’t work, remember you can find out the class of the object you need to style, as explained in the CSS section of this document.

  • Shiny prerendered
    In order to not slow down startup and load time, somet expensive data import and manipulation tasks could be done up front, via a proper use of runtime: shiny_prerendered instead of runtime: shiny.
    Guide: https://rmarkdown.rstudio.com/authoring_shiny_prerendered.html

Xaringan

  • Check available styles
    names(xaringan:::list_css())

  • Split slide in two

    .pull-left[
    content ...
    ]
    .pull-right[
    content ...
    ]
  • Issue with LaTeX math mode
    When using Xaringan, you have to use \\( ... \\) instead of \( ... \) for inline math mode. Therefore, it’s simpler to use $some math$ or $$some math$$ for mathematical equations, but make sure not to leave any space after and before the first and last dollar sign group, or else the equations will not be shown correctly.

    $\sin$    correct
    $ \sin $  incorrect
    $$\,\mathbb{R}\,$$    correct
    $$ \mathbb{R} $$ incorrect
  • Automatic update for xaringan presentation
    After knitting a xaringan presentation, if you execute the command xaringan::inf_mr() in the R console, the Rmd document will be automatically updated upon changes in its content, and the updated presentation will be continously shown in the RStudio viewer.
    After that, if you click in the Viewer section “Shown in new window”, the updated xaringan presentation will also be shown in your web browser.
    This option is very useful for online math classes, specially if you do not need to often use a “virtual pen”.

  • Long vertical slides
    In order to make the slides include a vertical scroll bar whenever the slide content goes beyond the usual limit, simply insert the following CSS code in your Xaringan document:

    .remark-slide-scaler {
      overflow-y: auto; /* only shows the scrollbar when required */
    }

    Due to this not being a well implemented feature of Xaringan nor remark.js, some problems can arise with such solution, as you can read in https://www.py4u.net/discuss/884501.
    However, this solution mostly works fine as long as you also include the following in your presentation:

    /* Hide counting number of current slide */
    .remark-slide-number {
      display: none; 
    }
    ---
    title: "Scrollable slides"
    output:
      xaringan::moon_reader:
        nature:
          navigation:
    # Disable mouse scrolling through slides to allow scrolling in slides
            scroll: false
    ---
  • Using Shiny with Xaringan
    Shiny does not work with Xaringan, even if you insert runtime: shiny in the YAML section.
    More info: https://github.com/yihui/xaringan/issues/204
    The recommended workaround is to publish the Shiny project online, for example in shinyapps.io/ and then insert in a slide via an iframe.
    Example:

    <iframe src="https://lucio-cornejo.shinyapps.io/dashboard_encuesta/" style="width: 100%; height: 100%;"></iframe>

Data Visualization

  • Plotly
    • Scatter plot
      Guide: https://plotly.com/r/line-and-scatter/
      Example:

      library(plotly)
      fig <- plot_ly(data=cars, x=~speed,y=~dist)
      fig <- fig %>% layout(
                            title="Speed vs Distance",
                            xaxis=list(title='Speed',range=c(0,30)),
                            yaxis=list(title="Distance",zeroline=FALSE)
                            )
      fig <- fig %>% add_trace(
                              text = ~paste("Speed: ",round(speed,2),"\nDistance: ",round(dist,2),sep=''),
                              hoverinfo = 'text',
                              marker=list(
                                          size=7.5,color='skyblue',
                                          line= list(color='rgb(255,0,0,.75)',width=1)
                                          )
                              )
      fig
    • Remove plotly graphic’s top bar with buttons

      fig <- plot_ly(...) 
      fig <- fig %>% config(displayModeBar= FALSE)
      fig
    • Boxplot
      Guide: https://plotly.com/r/box-plots/
      Example:

      plot_ly(mtcars,y=~wt,type='box') %>% layout(xaxis=list(showticklabels = F))
      
      # As of now, plotly does not have an option to not show in the graphic the outliers of the data
      # A not so good workaround (but probably the best one right now) to achieve that missing feature is the following:
      plot_ly(mtcars,y=~wt,type='box',marker=list(opacity=0)) 

      Plotly outlier missing property: https://github.com/plotly/plotly.js/issues/1953

    • Boxplot with respect to a pair of quantitative and qualitative variables
      Example:

      # Vertical boxplot
      plot_ly(iris,y=~Sepal.Length,color=~Species,type='box') %>% layout(xaxis=list(title='Species'),yaxis= list(zeroline=FALSE))
      
      # Horizontal boxplot
      plot_ly(iris,x=~Sepal.Length,color=~Species,type='box')

Web development

HTML

  • Headings
    There is up to 6 level headings, being <h6> last heading level </h6> the smallest one.

  • Create lists

    • Ordered list
      Example:

      <ol>
          <li>First item</li>
          <li>Second list</li>
      </ol>

      ol = Ordered list
      li = List item

    • Unordered list
      Example:

      <ul>
          <li>One item</li>
          <li>Another item</li>
      </ul>

      ul = Unordered list

  • Include an image

    <img src = "image.jpg" alt="name-for-image" width="number-of-pixels">
    Example:
    <img src = "pi.jpg" alt="sad_tree" width="1000">
    Where the image pi.jpg is in the same folder as the HTML file.
  • Add links

    Example of link to website:
    <a href="https://google.com">Click here</a> 
    Where "a" stands for "anchor".
    
    Example of link to html file in same folder as 
    the one you'd be working with:
    <a href="some-file.html">Click me</a>
  • Create a table
    Example:

    <body>
      <table>
          <thead>
              <tr>
                  <th>Ocean</th>
                  <th>Average Depth</th>
                  <th>Maximum depth</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td>Pacific Ocean</td>
                  <td>4200 m</td>
                  <td>10911 m</td>
              </tr>
              <tr>
                  <td>Atlantic Ocean</td>
                  <td>3646 m</td>
                  <td>8486 m</td>
              </tr>
          </tbody>
      </table>
    </body>

    Where the following stand for:
    thead: Table headings
    tr: Table row
    th: Table heading
    tbody: Body of the table
    td: Table data

  • Division of the page
    It’s not a division per se, but it works as a way to reference a certain section of the web page
    Example:

    <body>
      <div>
        content
      </div>
    </body>
  • Center a HTML table

    table {
      margin-left: auto;
      margin-right: auto;
    }
  • Define multiple classes for a HTML element
    Inside the < ... class="..."...>, you can only use class once, but multiple classes can assigned to some element via < ... class="class-1 class-2" ...>.
    Be careful with that option because a selection via [class="some-class"] will only select the elements that have one class only, the some-class one.
    Better use something like [class*="some-class"] instead.

  • Invalid characters inside a class name
    Some special characters can not be inside a class name, or they can but require special rules to deal with it.
    More information: https://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors

  • Center HTML input tag
    https://stackoverflow.com/questions/9264835/how-to-align-an-input-tag-to-the-center-without-specifying-the-width

  • Display text in only one line
    Add the CSS property white-space: nowrap; to what you wish any line break. To control whatever text that may not be displayed in the web page, use overflow: ... ;.
    For example, to hide the non shoen text, use overflow: hidden; .

  • Insert an element on top right corner of its container (parent tag)
    Example:

    <div style='position: relative;'>
          <button style='position: absolute; right: 0;'>Click me</button>
      </div> 

    Setting left 0 instead of right: 0 makes the button be positioned on the top left corner of its parent div.

CSS

  • Limitation
    Currently in Rmarkdown, CSS chunks only work with HTML ouput types, not with pdf. Therefore, LateX can come in handy to fix that gap.

  • Useful summary from Harvard University
    https://cs50.harvard.edu/web/2020/notes/0/

  • Get info of object to customize it with CSS
    Useful when the Rmarkdown output is html_document and you wish to customize some object from the web page. For Google Chrome, open the html file there and right click the object which you wish to customize, then click “Inpeccionar”/“Inspect”. A menu will appear and contain the necessary HTML data to get the class of the object you wish to customize, so, use that info in a CSS chunk in the Rmarkdown file.

  • Include a comment
    Example of CSS chunk:

    h1 {color: #EF99E3; }
    /* this is a comment */
  • Inline styling of a heading
    Examples:

    <h1 style="color: blue; text-align: center;">Welcome to my page</h1>
    
    ## Section 2 {style="color:red;"}
    
    ### Section 3 {onclick="alert('wow')"}
  • Not inline styling
    In the head section of a HTML document, you can include the style of HTML components via <style>.
    Example:

    <head>
      <title> Hello! </title>
      <style>
        h1 {
          color: blue;
          text-align: center;
        }
      </style>
    </head>

    Even better version:

    <head>
      <title> Hello! </title>
      <link rel="stylesheet" href="style.css">
    </head>

    Where the arbitrary file style.css only contains the relevant CSS code.

  • Set fonts
    Example:

    div { 
      font-family: Arial, sans-serif;
      font-size: 28px;
      font-weight: bold;
    }

    That way, the font sans-serif will be applied in case that the browser used does not recognize the other font, Arial in this case.

  • Apply styling to multiple objects
    Example:

    <style>
      td,th {
        border: 1px solid black;
        padding: 5px;
      }
    </style>
  • Basic table styling
    Example:

    <head>
      <title> Hello! </title>
      <style>
        table {
          border: 1px solid black;
          border-collapse: collapse;
          text-align: center;
        }
        td,th {
          border: 1px solid black;
          padding: 5px;
        }
      </style>
    </head>
    <body>
      <table>
          <thead>
              <tr>
                  <th>Nombre</th>
                  <th>Sexo</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td>Lucio</td>
                  <td>M</td>
              </tr>
              <tr>
                  <td>Lucía</td>
                  <td>F</td>
              </tr>
          </tbody>
      </table>
    </body>
  • Spacing between cells in a table
    Example:

    table {
      border-spacing: 10px 15px;
    }

    Such example establishes a vertical distance of 10px and a horizontal distance of 15px between the cells in a HTML table.

  • Referencing HTML objects
    You can use class to refer to a particular set of HTML objects; and, id, to refer to an unique HTML object.
    Example:

    <h1 id ="foo">Hello</h1>     Refer in CSS with #foo.
    <h2 class="fue">Hola</h2>    Refer in CSS with .fue

    The specificity CSS hierarchy works as follows:

    1. inline

    2. id

    3. class

    4. type

  • Style based on attributes
    Example:

    <head>
      <title> Hello! </title>
      <style>
          a {
            color: blue;
          }
          a[href="https://google.com"] {
              color: red;
          }
      </style>
    </head>
    <body>
      <ul>
          <li><a href="https://google.com">Google</a></li>
          <li><a href="https://facebook.com">Facebook</a></li>
      </ul>
    </body>
  • Hover use of selector :
    Example:

    <head>
      <title> Hello! </title>
      <style>
          button {
              background-color: green;
          }
          button:hover {
              background-color: orange;
          }
      </style>
    </head>
    <body>
      <button>Click me</button>
    </body>
  • Media queries
    Example:

    <head>
      <title> Hello! </title>
      <style>
          @media (min-width: 600px) {
              /*
              If width of page is 600px or larger, then perform:
              */
              body {
                  background-color: red;
              }
          }
          @media (max-width: 599px) {
              /*
              If width of page is 599x or smaller, then perform:
              */
              body {
                  background-color: blue;
              }
          }
      </style>
    </head>
    <body>
      <h1>Hello, world!</h1>
    </body>
  • Automatic wrapping of HTML content as page width changes
    Example:

    <head>
      <title> Hello! </title>
      <style>
          #test {
              display: flex;
              flex-wrap: wrap;
          }
          #test > div {
              background-color: blue;
              width: 200px;
              font-size:20px;
              margin: 20px;
              padding: 20px;
          }   
      </style>
    </head>
      <body>
        <div id="test">
          <div>1. Testeando ando pe joven. </div>
          <div>2. Testeando ando pe joven. </div>
          <div>3. Testeando ando pe joven. </div>
          <div>4. Testeando ando pe joven. </div>
          <div>5. Testeando ando pe joven. </div>
          <div>6. Testeando ando pe joven. </div>
          <div>7. Testeando ando pe joven. </div>
          <div>8. Testeando ando pe joven. </div>
          <div>9. Testeando ando pe joven. </div>
          <div>10. Testeando ando pe joven. </div>
      </div>
    </body>

    It does not seem to work in Rmarkdown when the content of <div> is a LaTeX equation.

  • Improve appearance on mobile
    Add the following line in the head of the HTML files:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

  • Grid
    Example:

    <head>
      <title>My Web Page!</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        .grid {
          background-color: green;
          display: grid;
          padding: 20px;
          grid-column-gap: 20px;
          grid-row-gap: 10px;
          grid-template-columns: 200px 200px auto;
      }
    
        .grid-item {
            background-color: white;
            font-size: 20px;
            padding: 20px;
            text-align: center;
        }
      </style>
    </head>
    <body>
      <div class="grid">
        <div class="grid-item">1</div>
        <div class="grid-item">2</div>
        <div class="grid-item">3</div>
        <div class="grid-item">4</div>
        <div class="grid-item">5</div>
        <div class="grid-item">6</div>
        <div class="grid-item">7</div>
        <div class="grid-item">8</div>
        <div class="grid-item">9</div>
        <div class="grid-item">10</div>
        <div class="grid-item">11</div>
        <div class="grid-item">12</div>
      </div>
    </body>
  • Bootstrap
    It’s a CSS library with a lot of presets to work with.
    To work with it, add the following line in the head of the HTML files:
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
    For more Information, visit this link.

  • Bootstrap HTML templates
    Visit this link to download some Bootstrap HTML page stylings.

  • Sass
    It’s pretty much CSS on steroids. Some of its additional features compared to CSS are defining variables, nesting and inheritance.
    Its files are of the type .scss and web browsers do not understand it. Therefore, you need to install Sass in order to convert the scss file into a css one and include it in the HTML document.

  • Action
    Example:

    <head>
      <title>Search</title>
    </head>
    <body>
      <form action="https://google.com/search">
        <input id="texto" type="text" name="q">
        <input id="boton" type="submit" value="Google Search">
      </form>
    </body>
  • Overwrite inline styling
    To beat the inline style specification, use !important.
    Example:

    h1 {
      color: red !important;
    }

    However, CSS code already with !important included can not be beaten by !important.

  • Text sensitive attribute selectors

    /* Select every cell containing word "male" */
    td[data-content="male"] {
      color: red;
    }
    
    /* Select every cell starting on "p" case insensitive */
    td[data-content^="p" i] {
      color: blue;
    }
    
    /* Select every cell containing "4" */
    td[data-content*="4"] {
      color: green;
    }
  • Underline text
    Example:

    div {
      text-decoration: underline;
    }
  • Underline text without breaking the line
    Example:

    <p>
      Only highlight 
      <span style="text-decoration: underline;">this</span>
      word.
    </p>
  • Change spacing between lines

    body {
      line-height: 22.5pt;
    }
  • Some selector examples
    Useful explanation from https://stackoverflow.com/questions/19931351/css-selectors-difference-between-body-h1-body-h1-and-body-h1:

    * body.h1 will select the body element if it has a class of h1.
        (ex. <body class='h1'>this one</body>)
    * body h1 will select all h1 elements in the body.
        (ex. <body><h1>this one</h1></body>)
        This is redundant in well-formed HTML, it will basically do the same thing as h1, 
        because the only place an h1 element can be (if your HTML is well-formed) is in the body)
    * body .h1 will select all the elements that have the h1 class in the body.
        (ex. <body><div class='h1'>this one</div></body>)
  • How to select parent but not its children
    Useful explanation: https://stackoverflow.com/questions/38520419/how-to-select-parent-and-not-child-in-css.

  • Select by lack of a certain property
    Useful explanation: https://stackoverflow.com/questions/30835168/is-there-an-opposite-css-pseudo-class-to-hover
    Example:

    .child:not(:hover){
      opacity: 0.3;
    }
  • Hiding objects
    Objects like tables, paragraphs, etc, can be hidden via at least two CSS properties: “display: none;” and “visibility: hidden;”
    But, using “visibility: hidden;” does not remove the space in the page occupied by such HTML object, while “display: none;” does.

  • Color linear gradient
    Example:

    td {
      background-image: linear-gradient(to right,rgba(255, 0, 0, 1) 50%,rgba(0, 0, 255, 1) 51%);
    }

    Such example splits the background color of the cells in a table with the left half as red and the right half as blue.
    Change the percentages to determine how the color gradient is applied.

  • Hide scrollbar but retain frunctionality
    In the following example, the class named hidden-scroll is the class of a tag which can be scrolled, but its scroll bar is not shown.
    This option can be very useful for long math equations displayed on a HTML document, due to the limitations of the MathJax library and how it displays LaTeX equations as images.

    /* Hide scrollbar for Chrome, Safari and Opera */
    .hidden-scroll::-webkit-scrollbar {
      display: none;
    }
    
    /* Hide scrollbar for IE, Edge and Firefox */
    .hidden-scroll {
      -ms-overflow-style: none;  /* IE and Edge */
      scrollbar-width: none;     /* Firefox */
    }

Javascript

  • Trigger action on certain button(s) after clicking some button
    Example:

    <input type="button" value="whatever" class="activar" onclick="sth()"></input>
    <input type="button" value="activation" onclick="gooo()"></input>
    
    <script>   
      function gooo(){
        $('.whatever').trigger('click');
      }
      function sth() {
        // content ...
      }
    </script>
  • Get characters of a string
    Example:

    let palabra = "hola";
    alert(palabra.charAt(0)); // Displays the word "h".
  • Remove characters from a string
    This method involves turning a string into array of its characters, removing some elements of such array and then join the characters left into a new string.
    Example:

    let t = document.querySelector('div');
    // t is a div which contains some text
    
    //  Convert string into array of characters
    let texto = t["textContent"].split(''); 
    
    // Remove the first two characters of the string
    texto.splice(0,1); texto.splice(0,1);
    
    // Remove the last two characters of the string
    texto.splice(texto.length - 1 ,1); texto.splice(texto.length - 1,1);
    
    // Set the initial text to its new value after joining the characters into a new string
    t["textContent"] = texto.join('');
  • Play a sound multiple times
    When you use a function like “click this and something will sound”, as it’s common with virtual pianos, there may be a problem where, after click the sound button, you have to wait till the sound stops in order for the next button click to activate the same sound.
    The problem can be fixed using currentTime = 0; right before play();. Example:

    <audio id="nota" preload="auto"><source src="musical_notes/C4.mp3"></source></audio>
    <div id="sonido">
      <p>Click me to play a sound</p>
    </div>
    <script>
      let audio;
      document.getElementById(sonido).addEventListener('click',function() {
        audio = document.getElementById(nota);
        audio.currentTime = 0;
        audio.play();
      }
    </script>
  • Convert a HTML collection into an array
    Most efficient way:

    let converted_array = Array.prototype.slice.call( some_html_collection );
  • Set a time delay
    Example:

    <body>
          <button onclick="doIt()">Do it</button>
          <script>
              function sleep(ms) {
                  return new Promise(resolve => setTimeout(resolve, ms));
              }
              async function doIt(){
                  for(var i=0;i<18;i++){
                      console.log(i.toString())
                      await sleep(100);
                  }
              }
          </script>
      </body>
  • Get IP of webpage visitor, using Javascript
    Example using JQuery:

    // IPs of the visitors to this website for which
    // we grant permission to see the content of the site.
    const IP_exceptions = ['161.123.234.45','161.133.243.54']; 
    
    let pagina = document.querySelector('html');
    
    $.getJSON("https://jsonip.com/?callback=?", function (data) {
      if( !( IP_exceptions.includes(data['ip']) )) { 
        // IP of user does not belong to someone granted permission to see site,
        // so we delete the content of the website
        pagina.remove();
      } else {
        pagina.style.visibility = 'visible'; 
        // this webpage had 'hidden' visibility when loaded
      }
    });

LaTeX

  • Cheat sheet
    This summary of LateX commands is from an online LateX course.

  • List of LateX symbols
    The Comprehensive LATEX Symbol List

  • LateX fonts
    The LateX Font Catalogue

  • Customize geometry of Rmarkdown pdf output
    You can set the geometry in the YAML section.
    Examples:

    geometry: "left=5em,top=2.5em,right=5em,bottom=6em"
    
    geometry: "landscape"
  • Math equations

    \( ... \) for inline math expressions.
    \[ ... \] for display-style expressions.
  • Include LateX packages in rmd file
    In the YAML section of the Rmarkdown document include some text as in the following example:
    header-includes:
         - \usepackage{unicode-math}
         - \usepackage{ragged2e}

  • Pdf output
    In order to avoid certain problems with LateX when the ouput file is pdf, I suggest you add the following to the YAML section of the rmd document:

    output: 
      pdf_document:
          latex_engine: xelatex
  • Efficient way to find the LateX code for symbols
    This site allows you to draw a symbol and it will output various possibilities for which LateX code to use in order to use that symbol (or an approximation of it in case your drawing is kinda bad).

  • Spacing
    The ragged2e package does not seem to work when the output is html, but it does when the output is a pdf file. In that case, you may use functions such as

    \kern2em
    \vspace{1ex}
    \hspace{10ex}
  • Inline display style
    For prettier inline math equations can be made possible for symbols like \int, \lim, \prod, ..., via \displaystyle{ }.
    Comparison:
    \lim_{h\to\, 0} \(\quad\Rightarrow\quad \lim_{h\to\, 0} \quad .\)
    \displaytyle{\lim_{h\to\, 0}} \(\quad\Rightarrow\quad \displaystyle{\lim_{h\to\, 0}} \quad.\)

  • Cartesian product symbol
    \(\times\) as \times

  • Function composition symbol
    \(\circ\) as \circ

  • Reverse symbol of “belongs in”
    \(\in\) as \in and \(\ni\) as \ni.

  • Inner product symbol
    \langle u,v \rangle \(\quad\Rightarrow\quad \langle u,v \rangle \, .\)

  • Basic structure of a book in LateX

    documentclass{book}
    \title{LaTeX Document}
    \author{Wikipedia \\ Collated by Firuza}
    \date{\today}
    \begin{document}
      \maketitle
      \tableofcontents
    
      \chapter{Overview}
    
      \section{Overall Description}
    
      \section{Introduction}
      \paragraph{}
      Dhansak is a popular Indian dish, originating among the Parsi Zoroastrian community.
    
      \subsection{Purpose}
    \end{document}
  • Avoid entry in table of contents
    Possible using * as in the following examples:

    \chapter*{Introduction}
    \subsection*{Time-table}
  • Proper quotes use
    ` for the opening of quotes, and ' for closing them.

  • Set margin of the pages
    Example:

    % Write between documentclass{article} and begin{document}
    \usepackage[a4paper,margin=2in]{geometry} % 2 inches in all 4 sides of the page
    \usepackage[a5paper,top=1in,left=2in,right=0.75in,bottom=1in]{geometry}
    
    % Write between documentclass{book} and begin{document}
    \usepackage[inner= 1.5in,outer=0.5in]{geometry}
  • Remove page numbering

    % Insert in the document environment
    \pagenumbering{gobble}
  • Customize the page numbering
    For a book document class, one can set when to start counting the pages via \setcounter{page}{1}.
    I prefer the following customization for the beggining of a book:

    \begin{document}
      \maketitle
      \pagenumbering{gobble}
    
      \tableofcontents
      \pagenumbering{roman}
    
      \chapter{Introduction}
      \setcounter{page}{1}
      \pagenumbering{arabic}
    
      \section{blank}
      % ...
    
    \end{document}
  • Rotate page content by 90 degrees

    \usepackage{lscape}
    
    \begin{document}
    
      \begin{landscape}
    
        Content to be presented in the rotated page.
    
      \end{landscape}
    
    \end{document}
  • Make pdf easier to read online
    If the pdf document will most likely be read in a pc, it becomes easier to do so if you include \usepackage[landscape]{geometry}. That way, everything inside the document environment will be affected by the landscape environment.

  • Page break vs new page
    From stackexchange:
    \pagebreak tries to make the page the same height as other pages if it’s possible (by stretching intervals between paragraphs etc) and \newpage just fills the page with empty space.

  • Insert footnote
    Example:

    % Inside the document environment
        arbitrary text to be footnoted \footnote{content of this footnote}
  • Column formatting

    • For just two columns, you can set \documentclass[twocolumn]{...}.

    • For more than two columns, no need to alter the documnt class, but add instead \usepackage{multicol} and incude the text to be columnized in the proper environment:

    \begin{multicols}{n} % n is the number of columns
      % content
    \end{multicols}
    • Change the distance between columns with \setlength{\columnsep}{20pt}, where its last argument defines such distance.

    • Add a bar to separate the columns with \setlength{\columnseprule}{1pt}, where its last argument defines the thickness of the bar.

    • Set where to start the next column with \columnbreak .

  • Changing font size
    To set the new font size for the rest of the document, type, for example, \large; but, if you only want to apply a font size to a specific part of the text, type, for example, {\large content ...} .

  • Customizing text color
    Example:

    \documentclass{article}
    \usepackage[dvipsnames]{xcolor} 
    
    \begin{document}
    
      % Mix white with 60% of red
      \pagecolor{red!60}    
    
      % Mix blue with 10% of red
      \textcolor{red!10!blue}{texto}
    
    \end{document}
  • Aligning text
    By default, LateX’s text is fully justified, but you can change it via:

    \begin{document}
    
      \centering
      texto
    
      \flushleft
      texto
    
      \flushright
      texto
    
      \justify    % This one requires the package ragged2e
      texto
    
    \end{document}
  • Spacing

    % For the space between lines of text, the following commands set a new standard for the WHOLE document:
    \singlespacing
    \onehalfspacing
    \doublespacing
    
    % You can also set a custom spacing using the setspace package:
    \spacing{X}
    
    \begin{spacing}{X}
    ...
    \end{spacing}
    
    % Basic vertical spacing commands:
    \vspace{Xpt}
    \smallskip
    \medskip
    \bigskip
    \vfill    % Very useful for typing the "cover" of a document.
    
    % Basic horizontal spacing commands:
    \    % Adds a single space
    \,
    \hspace{Xpt}
    \hfill
  • Create lists

    % Types of lists
    \begin{itemize | enumerate | description}
    \item ...
    \item [...] ...    % Used only with description
    \end{itemize | enumerate | description}
    
    % There is a limitation of 4 levels (list inside list) nesting.
    
    % Change numbering style
    \usepackage{enumerate} \begin{enumerate}[...]
    
    % Change bullet Style
    \usepackage{amssymb}
    \renewcommand{\labelitem<Level>}{$<Style>$}
    
    Examples:
    \renewcommand{\labelitemi}{$ \diamond $}
    \renewcommand{\labelitemii}{$ \cdot $}
  • Create matrix
    Example:

    % Requires the package amsmath 
    $
      \begin{pmatrix}           % ( ) symbols for matrix
        a_{11} & a_{12} \\    % New row 
        a_{21} & a_{22}       
      \end{pmatrix}
      \kern2em
      \begin{bmatrix}           % [ ] symbols for matrix
        a_{11} & a_{12} \\     
        a_{21} & a_{22}       
      \end{bmatrix}
      $
    
    % No extra package required
    
    \[ \left(\begin{array}{ccc}
      1 & 2 \\
      2 & 4 
    \end{array}\right) \]
  • Create equation
    Example:

    \begin{equation}
        \cos^2 x - \sin^2 x = \cos(2x)
    \end{equation}
    % It automatically becomes centered and the equation number is displayed.
  • Align equations
    Example:

    % Requires the package amsmath 
    \begin{align}
        x^2 - 2x &= -1   \\                 % New line 
        x^2 -2x +1 &= 0  \nonumber\\  
        % The & symbol sets the following character in the same horizontal position
        (x-1)^2 &= 0     \nonumber\\
        x &= 1                 \nonumber   
        % \nonumbber means "do not label this equation"
    \end{align}
  • Create a table
    Example:

    \begin{tabular}{clrp{4cm}}
      No. & Item & Price & Qty \\ 
      1   & Mouse & 10 &  1    \\
      % & separates columns
      % \\ is for new row
      % c: center; l: left; r: right
      % p{Xcm} sets a length of X cm for such column.
    \end{tabular}

    Add lines:

    \begin{tabular}{|c|l|l|r|}    % Each | is a vertical line
      \hline    % horizontal line
      No. & Item & Quantity & Price \\
      \hline
      1 & Pen & 3 & 10 \\
      \cline{1-2} \cline{4-4}    
      % Horizontal line between columns 1 and 2
      % Horizontal line for column 4
      2 & Pencil & & 5 \\
      \hline
    \end{tabular}

    You can use the package arydshln to apply dashed lines instead, via:

    \hdashline[size of dash / space between dashes]
    \cdashline {i-j}[size of dash / space between dashes]
    % The vertical dashed line is used with, for example:
    % \begin{tabular}{:c:l:l:r:}
  • Merge table’s rows or columns
    Merge rows:

    % Requires the package multirow and the command
    % \multirow{Numbe_of_rows}{width}{content}
    % Example:
    \begin{tabular}{|c|l|l|r|}
      \hline
      No. & Item & Quantity & Price \\
      \hline
      1 & Pen & \multirow{2}{*}{3} & 10 \\
      ...
    % The * symbol is to keep the previously length of such column
    % Rows 2 and 3 got merged

    Merge columns:

    % Does not require to add a package
    % Example:
    \begin{tabular}{|c|l|l|r|}
      \hline
      \multicolumn{4}{|c|}{Stationery Items} \\ 
      % Four columns have been merged
      \hline
      No. & Item & Quantity & Price \\
      ...
  • Change the spacing for tables
    Insert the command \renewcommand{\arraystretch}{value} before the tabular environment. The default “value” is 1, but 1.5 works better, in my opinion.

  • Table that spans more than one page
    To address this problem, when using the tabular environment, use the package longtable and change the environment of the table to longtable, instead of tabular.
    If you wish that the first \(n\) rows of your table get repeated in every page that your table spans, insert \endhead right after the last row you wish to be repeated.

  • Table environment
    It allows us to add captions and change the position of the table:

    • Environment:
    \begin{table}[position]
      your tabular code
      \caption{...}
    \end{table}
    
    % Position:
    % t: Insert table at top of the page.
    % b: Insert table at bottom of the page.
    % h: Insert table approximately here.
    • You can create a “table of contents” analogue for the tables, via the command \listoftables .
  • Include images
    It requires the graphicx package, which supports
    jpg, png, eps and pdf files. The image must be in the same folder as the tex file.

    • Scaling
    \includegraphics{image.jpg}
    \includegraphics[height=4cm]{image.pdf}
    \includegraphics[width=4cm]{image.png}
    
    % The following example is not recommended, due to changing the 
    % proportions of the image.
    \includegraphics[width=4cm, height=4cm]{image.eps}
    
    \includegraphics[scale=0.5]{image.png}
    • Crop
    \includegraphics[clip=true, trim=15mm 5mm 7mm 3mm]{image.png}
    • Rotate
    \includegraphics[angle=60]{image.png}
    • Add an image border
    \fbox{ \includegraphics... }
    
    % Adjust the border thickness with:
    \setlength{\fboxrule}{2pt}
    
    % Change the distance bewtween the image 
    % and its border with:
    \setlength{\fboxsep}{15pt}
    
    % Both last commands only affect the
    % \includegraphics{...} that appear after them.
  • The figure environment
    It allows us to position the figure and add a caption to it.
    Example:

    \begin{figure}[position]
      \includegraphics[...]{...}
      \caption{...}
    \end{figure}

    You can add a “table of contents” analogue for the figures with \listoffigures .

    • Add sub-figures It requires the packages caption and subcaption .
      Basic structure:

      \begin{figure}[<position>]
        \begin{subfigure}{<width>}
          \includegraphics...
          \caption{...}
        \end{subfigure}
        ...
        \caption{...}
      \end{figure}

      Example:

      \begin{figure}
        \centering
        \begin{subfigure}{0.3\textwidth}
        % Notice the necessary "0.3" because we include 3 figures.
        % For just two figures, "0.4" would have sufficed.
          \centering
          \includegraphics[width=\textwidth]{image.png}
          \caption{Original Image}
        \end{subfigure}
        \hfill % So that the sub figures aren't right next to each other.
        \begin{subfigure}{0.3\textwidth}
          \centering
          \includegraphics[width=\textwidth, angle=90]{images/parrot.png}
          \caption{Rotated by 90 degrees}
        \end{subfigure}   
        \hfill
        \begin{subfigure}{0.3\textwidth}
          \centering
          \includegraphics[width=\textwidth, angle=90]{images/parrot.png}
          \caption{Rotated by 90 degrees}
        \end{subfigure}   
        \caption{Image of a Parrot}
      \end{figure}

      If you leave blank lines in the figure environment, the subfigures may not be shown in the same line.
      To remove the "(a)" automatic label of the subfigure caption, include \captionsetup[subfigure]{labelformat=empty} in the beggining of the document environment.

  • Creating the cover
    It’s done in the titlepage environment.
    Example:

    \begin{titlepage}
        \centering
    
        \huge
        \textbf{Car\'atula}
        \vfill
    
        \Large
        \textbf{Submited by } \\
        \medskip
        Lucio Cornejo
        \vfill
    
        PUCP
        \vfill
    
        August  4
        \vfill
    
        2021  
    \end{titlepage}

    LateX will automatically not number the page of "titlepage", and it will begin counting the pages from the next page instead.

  • Include hyperlinks and hypertext
    It requires the packages url and hyperref.
    Display a link with, for example, \url{https://www.google.com/} .
    Create hypertext with \href{https://www.overleaf.com}{Overleaf}, where the second { } contains what will be displayed but takes you when clicked to the url denoted.

    • Cross referencing
      Label a section, subsection, table, figure or page number via \label{KEY}, and refer to them via the following:
    \ref{KEY}     % Outputs the index number of such object labelled.
    \pageref{KEY} % Outputs the page number of such object labelled.
    
    % This command requires the package hyperref
    \nameref{KEY} % Outputs the bane of such object labelled.
  • Beamer presentation

    • Creation
      Set beamer as the document class.

    • Themes
      Here are some popular themes and colorthemes for beamer.
      Example:

      \usetheme{Berkeley}
      \usecolortheme{default}
    • Create a slide

      \begin{frame}[t|c|b]{Frame Title}
        ...
      \end{frame}
      
      % The [.] and {.} next to {frame} are optional.
      % [t] sets the content to the top of the page;
      % [b], to the bottom, and; [c], to the center.
    • Table of contents
      Same command: \tableofcontents

    • Insert boxes

      % Add block
      \begin{block}{Title}
        ...
      \end{block}
      
      % Add alert 
      \begin{alertblock}{Title}
        ...
      \end{alertblock}
      
      % Add example(s)
      \begin{example}
        ...
      \end{example} 
      % The example environment does not allow to set it a title.
    • Insert columns

      % Environment
      \begin{columns}
        \column{X\textwidth}
        content of this particular column
        ...
      \end{columns}
    • Automatically add necessary frames
      If one frame environment contains so much content that not all of it can get displayed in one slide, simply change the frame environment as follows:

      \begin{frame}[allowframebreaks]{title}    
        ...
      \end{frame}

      Now the missing content will be displayed in the necessary amount of slides.

    • Set a pause
      You can pause the display of lists, blocks, text, etc.
      Example:

      \begin{frame}
            \begin{itemize}
                \item 1 \pause
                \item 2 \pause
            \end{itemize}
      
        \vfill
      
            \begin{itemize}
                \item<2-> 1  % Show this item second.
                \item<1-> 2  % Show this item first.
            \end{itemize}
        \end{frame}
      
        \begin{frame}
            \begin{block}{Theorem}
                \pause
                For all $ \theta \in \mathbb{R} $, it holds 
                $ \cos^2\theta + \sin^2\theta = 1 \; . $
            \end{block}
            \pause
      
            \begin{alertblock}{Extra}
                Also true if $ \theta $ is a complex number.
            \end{alertblock}
        \end{frame}
    • Change view of about to be displayed content

      % Show in transparent the content about to be displayed
      \setbeamercovered{transparent}
      
      % Hide the content about to be displayed
      \setbeamercovered{invisible}
    • Special title, author, institution and logo
      Sometimes the set \title{...}, \author{...}, ... can be too long to fit in the space provided by the beamer theme used. Therefore, you can add alternative values to those categories to appear in the proper beamer section.
      Example:

      \documentclass{beamer}
      \usetheme{Madrid}
      \usecolortheme{default}
      
      \title[Animals and Flowers]{Basic Information about Wild Animals and Flowers}
      \author[Firuza]{Firuza Karmali}
      \institute[IIT Bombay]{{\large Indian Institute of Technology Bombay}}
      \logo{\includegraphics[height=1cm]{pi.jpg}}
      
      % The content in [] will appear in the bottom section of each beamer slides,
      % while the content in {} will appear in the slide where \maketitle is applied.
      % The logo will appear at the bottom right of every slide.
    • Change the color of objects in Beamer

      % Theme color
      \setbeamercolor{structure}{fg=color}
      
      % Tertiary
      \setbeamercolor{palette tertiary}{bg=color, fg=color}
      
      % Secondary
      \setbeamercolor{palette secondary}{bg=color, fg=color}
      
      % Primary
      \setbeamercolor{palette primary}{bg=color, fg=color}
      
      % Title
      \setbeamercolor{title}{bg=color, fg=color}
      
      % Frame Title
      \setbeamercolor{frametitle}{bg=color, fg=color}
      
      % Slide background 
      \setbeamercolor{background canvas}{bg=color}
      
      % You can also use the "!proportion" command to mix colors 
      % in the "color" section after "bg=" or "fg=".
    • Specify the aspect ratio of the slides

      % 16:9
      \documentclass[aspectratio=169]{beamer}
      % 4:3
      \documentclass[aspectratio=43]{beamer}
  • Add curved line on top of symbol
    Example:
    \(\widetilde{M}\) as \widetilde{M} .

  • Create a diagram
    Example:

    \documentclass{article}
    \usepackage{tikz-cd}
    \begin{document}
      \[
      \begin{tikzcd}
        U \arrow[r,"f"] &
        V  
        \\
        \widetilde{U} \arrow[u,"\varphi"]\arrow[r,swap,"Id"] &        
        \widetilde{U} \arrow[u,swap,"\phi\circ\widetilde{f}"] 
      \end{tikzcd}
      \]
    \end{document}

    It does not seem to work natively in Rmarkdown.

  • Symbol for orthogonal vector
    \perp \(\Rightarrow \; \perp\)
    \not\perp \(\Rightarrow \;\not\perp\)

  • Horizontal braces
    Examples:
    \(\underbrace{f \circ \alpha}_{\beta}\) as \underbrace{f \circ \alpha}_{\beta}.

    \(\overbrace{\mathbb{R}^n \times\cdots\times\mathbb{R}^n}^{n \text{ veces}}\) as \overbrace{\mathbb{R}^n \times\cdots\times\mathbb{R}^n}^{n \text{ veces}}.

  • Norm symbol
    Instead of using twice double \mid, try \lVert x \rVert for \(\lVert x \rVert \, .\)


Git

  • Useful summary from Harvard University
    https://cs50.harvard.edu/web/2020/notes/1/

  • Clone a repository
    Copy the contents of a git repository into your computer.
    Command:
    git clone url-of-repository
    If the repository is private, it’s better to use the following command:
    git clone https://username@github.com/username/repo_name

  • Command commit
    It saves the current state of all the files, folders and assets in the repository, that have been added.
    Structure: git commit -m "message"
    The ‘message’ section can be useful to keep track of which changes, or a summary of them, were made to the project.

  • Command add
    It tells Git to add a file as one to track the next time we use the commit command.
    Use git add . to add all the changes in the repository that you’ve made.

  • Command status
    Useful if you need to compare the local version of your repository, with the one on GitHub.

  • Command push
    It pushes to GitHub the local changes to the repository so that the online version of the repository has the same contents as the local version on your computer.

  • The git trifecta
    git add selects changes.
    git commit records changes LOCALLY.
    git push shares changes.

  • Merging add and commit
    You can add and commit a file via one command via:
    git commit -am "message"

  • Command pull
    It pulls the most recent changes down from a repository in GitHub, into the local version of such repository.

  • Command log
    It shows the changes made in each commit, by who and when.

  • Command reset
    Example:
    git reset --hard origin/master
    Such example resets back the current local version of the repository, to however it is on GitHub.

  • Command branch
    It shows you which branch you are currently on (with *) and which branches exist in my repository.

  • Create a branch
    git checkout -b name_of_branch.
    Now, the changes made will not affect the master branch, as long as we stay on this branch.

  • Change branch
    Return to the master branch:
    git checkout master

  • Combine changes of branches
    Say you have two branches: master and style.
    If you are currently in the master branch, then execute:
    git merge branch_name
    You may have to deal with merge conflicts, but, if you avoid making distinct branch modifications to the same line of code, the merge may work out.

  • GitHub pages
    You can create your own website using GitHub.
    A simple example is to create a repository named your_username.github.io and add a file named index.html of the type:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>
          My site!
        </title>
      </head>
      <body>
        <h1>This is my  GitHub Pages website!</h1>
      </body>
    </html>
  • Fork
    It’s the GitHub functionality that allows you to copy the contents of some repository so that you can push and pull from its new copy as if itw as your own.
    It’s pretty useful for open-source software.

  • Replace master branch by another branch
    Explanation: https://stackoverflow.com/questions/2862590/how-to-replace-master-branch-in-git-entirely-from-another-branch.
    Example:

    git checkout branch_two_name
    git merge -s ours master
    git checkout master
    git merge branch_two_name
  • Delete a branch
    Explanation: https://stackoverflow.com/questions/2003505/how-do-i-delete-a-git-branch-locally-and-remotely.
    Example:

    git branch -d branch_name
    # -d only works for deleting the branch if it has already been fully merged in its upstream branch.
    git branch -D branch_name
    # -D works for deleting the branch irrespective of its merged status.


Python

  • Useful notes from a course in Harvard University
    https://cs50.harvard.edu/web/2020/notes/2/

  • Define a class
    A class in Python is a template for a type of object.
    Examples:

    # Example 1:
    class Point():
        def __init__(self,input1,input2):
            self.x = input1
            self.y = input2
    
    p = Point(0,1)
    print(p.x)
    print(p.y)
    
    # Example 2:
    class Flight():
        def __init__(self,capacity):
            self.capacity = capacity
            self.passengers = []
    
        def add_passenger(self,name):
            if self.open_seats()==0:
                return False
            self.passengers.append(name)
            return True
    
        def open_seats(self):
            return self.capacity - len(self.passengers)
    
    flight = Flight(3)
    people = ["Harry", "Ron", "Hermione","Ginny"]
    
    for person in people:
        if flight.add_passenger(person):
            print(f"Added {person} to flight.")
        else:
            print(f"No available seats for {person}.")
  • Define a decorator
    A decorator is a function that takes a function as an input and returns a modified version of that function as an output.
    Example:

    def announce(f):
        def wrapper():
            print("About to run the function...")
            f()
            print("Done with the function.")
        return wrapper
    
    @announce
    def hello():
        print("Hello, world!")
    
    hello()
  • Change a string’s characters
    Python does not allow to change the characters of a string, but you can work around it by transforming the string into a list, altering such list’s elements and then merge them and transform it into a string.
    Example:

    # String: string_1
    
    word = list(string_1)
    word[1] = "e"
    palabra = ""
        for i in word:
            palabra = palabra + str(i)
    
    # "palabra" is the new altered string.