R

R can be used as a shell by pointing to the R binary. The quickest way is with the built-in profile:

extensions:
  term:
    profile: r

This sets shell: R, shell-args: ["--no-save", "--no-restore", "--quiet"], prompt: ">", and ps2: "+". You can override any of these, for example to load a library at startup:

extensions:
  term:
    profile: r
    init: "library(dplyr)"

Note: wrap > and + in backticks in YAML since pandoc interprets bare > as a blockquote marker and + as a list item.

Basic Usage

cat("Hello from R", R.version.string, "\n")
Hello from R R version 4.3.3 (2024-02-29)

Vectors and Arithmetic

x <- 1:10
mean(x)
[1] 5.5
sd(x)
[1] 3.02765

Data Frames

df <- data.frame(name = c("Alice", "Bob", "Carol"), age = c(30, 25, 35))
df[df$age > 26, ]
   name age
1 Alice  30
3 Carol  35

Functions

fibonacci <- function(n) {
  a <- 0; b <- 1
  for (i in seq_len(n)) {
    tmp <- b
    b <- a + b
    a <- tmp
  }
  a
}
sapply(1:10, fibonacci)
 [1]  1  1  2  3  5  8 13 21 34 55

Apply and Pipes

mtcars |> head(5) |> subset(select = c(mpg, cyl, hp))
                   mpg cyl  hp
Mazda RX4         21.0   6 110
Mazda RX4 Wag     21.0   6 110
Datsun 710        22.8   4  93
Hornet 4 Drive    21.4   6 110
Hornet Sportabout 18.7   8 175