loading...

The R package {knitr} is used to insert R code withing your Markdown document, which makes altogether an R Markdown document, usually with the .Rmd extension. Go to {knitr} homepage for more details. This document uses various chunks to see how they appears in a {pkgdown} site with the {svPkgdown} style.

R chunks

  • A few R commands:
# This is a comment (don't use ##, since it is reserved for output!)
a <- 1 + 1 # Another comment
TRUE; NA; "Some text"
## [1] TRUE
## [1] NA
## [1] "Some text"
summary(cars) # A table
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00
  • Normal output versus message versus warning versus error:
# Normal output
cat("Some text...\n")
## Some text...
# A message
message("My very nice message")
## My very nice message
# Output with a warning
1:2 + 1:3
## Warning in 1:2 + 1:3: longer object length is not a multiple of shorter object
## length
## [1] 2 4 4
# An error
non_existing_object
## Error in eval(expr, envir, enclos): object 'non_existing_object' not found
  • R chunk with option to generate a plot:
An example figure generated by R, from the `cars` dataset.

An example figure generated by R, from the cars dataset.

  • Another plot:
library(ggplot2)
qplot(speed, dist, data = cars) + geom_smooth(method = "loess")
## Warning: `qplot()` was deprecated in ggplot2 3.4.0.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'
Distance in function of speed for the `cars` data set.

Distance in function of speed for the cars data set.

Inline R expressions and special chunks

  • Inline R expression like 2, or R version 4.4.1 (2024-06-14).

  • Rcpp code chunks can also be included in your document:

#include <Rcpp.h>

// [[Rcpp::export]]
int fibonacci(const int x) {
    if (x == 0 || x == 1) return(x);
    return (fibonacci(x - 1)) + fibonacci(x - 2);
}

Because fibonacci() was defined with the Rcpp::export attribute it can now be called as a normal R function:

fibonacci(10L)
## [1] 55
fibonacci(20L)
## [1] 6765
  • An R chunk that is displayed, but not executed:
library(knitr)
knit('R Markdown V2 Syntax.Rmd')