Capítulo24 Opciones de Knitr

## [1] "2026-08-01"

La mayoría de los ejemplos y ideas de esta sección proviene de yihui en el siguiente website <https://yihui.org/knitr/>

el paquete knitr fue diseñado para ser transparente para generar reporte de R, añadiendo componente de animación y Latex (Ecuaciones) y otras funciones.

Hay muchas opciones para determinar lo que hace un chunk

  • Code evaluation: evaluación de código
  • Text output: Formateo de texto
  • Code decoration: Decoración del código
  • Cache: Cache
  • Plots: Gráficos
  • Animation: Animaciones
  • Code chunk: Código del chunk
  • Child Document: Documento asociados
  • Language engines: Asociación de lenguaje
  • Option Template:
  • Extracting source code:
  • Other chunk options:
  • Package Options:
  • Global R Options:

24.1 Para ver las opciones de knitr de los chunk

knitr fue creado por Yihui Xie en 2012; es el motor que ejecuta el código de R dentro de los documentos R Markdown y “teje” (knit) el resultado junto con el texto. Sustituyó a Sweave con una sintaxis más flexible.

Opciones de los chunks — controlan qué se muestra.

  • echo=FALSE: oculta el código (muestra solo el resultado).
  • eval=FALSE: muestra el código pero no lo ejecuta.
  • include=FALSE: ejecuta el código pero no muestra nada.
  • warning=FALSE / message=FALSE: ocultan avisos y mensajes.
  • fig.width / fig.height / out.width: tamaño de las figuras.

Este chunk es para que la información de los chunk en la parte de knitr se vea.

library(knitr)
hook_chunk = knit_hooks$get('chunk')
knit_hooks$set(chunk = function(x, options) {
  if (!is.null(options$echo_opts)) {
    return(paste0("```` ```{r ", options$params.src, "} ````", x, "```` ``` ````"))
  } else {
    return(hook_chunk(x, options)) # pass to default hook
  }
  })

opts_knit$set(eval.after = 'fig.cap')

Los ejemplos aquí serán limitados a las alternativas para los documentos .Rmd

  • Las opciones están escrita de forma de tag=selección de la alternativa.

Opciones de bloques

Se personaliza los bloques con “opciones” options de los chunks.

En la rueda de a la derecha de cada chunk hay opciones para seleccionar opciones.

24.2 Tablas de opciones principales

Opción Ejecuta Muestra Output Gráficos Mensajes Advertencias
eval=FALSE - - - - -
include=FALSE - - - - -
echo=FALSE -
results=“hide” -
fig.show =“hide” -
message=FALSE -
warning=FALSE -
error=FALSE -
  • Comenzando con dándole un nombre al chunk “mi-chunk”

Ponerle nombre a cada chunk (como mi-chunk) facilita localizar errores, navegar por el documento y reutilizar el caché de los cálculos costosos.

library(tidyverse)

algun_nombre, echo=TRUE


Eso es lo que va a ver cuando hace el knit

library(tidyverse)

Nota aquí tengo include=FALSE, por consecuencia cuando se hace un knit, no se ve lo que hay en el chunk.
- Ahora cambialo a TRUE

head(cars)
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10

```{r c22-7, include=TRUE, echo_opts=TRUE}

head(cars)
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10

```


Añade una figura

data=c(1:100)
mean(data)
## [1] 9.6

```{r c22-11, include=TRUE, fig.cap='El nombre de mi figura.', fig.topcaption=TRUE, echo_opts=TRUE}

plot(cars)

Figure 24.1: El nombre de mi figura.

El nombre de mi figura.

```


```{r c22-12, include=TRUE, fig.cap= "An incredible figure", echo_opts=TRUE}

library(ggplot2)
df <- data.frame(letters = letters[10:15], value = 1)

ggplot(df, aes(letters, value, fill = letters)) +
 geom_bar(stat = "identity")
An incredible figure

Figure 24.2: An incredible figure

```


```{r c22-13, include=TRUE, fig.cap= "An incredible figure", fig.width = 3, fig.height = 3, echo_opts=TRUE, echo=FALSE}
An incredible figure

Figure 24.3: An incredible figure

```


Figure alignment: default, left, right, and center

fig.align

```{r c22-14, include=TRUE, fig.cap= "caption", fig.width = 3, fig.height = 3, fig.align='right', echo_opts=TRUE}

library(ggplot2)
df <- data.frame(letters = letters[1:5], value = 1)

ggplot(df, aes(letters, value, fill = letters)) +
 geom_bar(stat = "identity")
caption

Figure 24.4: caption

```


Wrap text around figure

Use ese código para que el texto “wraps” alrededor de las figura (ese código es de otro idioma de computadora de se llama css)

AQUI el CHUNK

24.2.0.0.1 R Markdown wrapping

código css

caption

Figure 24.5: caption

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

Note that the echo = TRUE parameter was added to the code chunk to have printing of the R code that generated the plot.



24.2.1 OTRAS funciones de knitr

  • eval= to evaluate the code FALSE or TRUE
  • echo = TO show the code FALSE or TRUE
  • message = FALSE or TRUE
  • warning = FALSE or TRUE
  • error =FALSE or TRUE
  • results = ‘asis’ To show text exactly as printed/written
##  [1]  1  2  3  4  5  6  7  8  9 10
library(MASS)
library(dplyr)
library(MASS)
cat("I'm raw **Markdown** content.\n",
    "\n",
               "➪ My poetry of Puerto Rico\n")

I’m raw Markdown content.

➪ My poetry of Puerto Rico



24.3 Emoji or Symbols

24.3.1 Select Under the Edit ➡ Emoji & Symbols.

24.3.1.0.1 Remember you can add emoji’s to your document

Sometimes you want to 🙈 around a bit and add some ⭐️⭐️ to your document. 🎈🎈 Well we have a gift for you if you add interesting emoji’s to your document, above all if you are a 🎶.