R/format_as_code.R
format_as_code.Rd
Function prints object, captures the output and formats it so that it will be printed as a piece of code in a Markdown file.
format_as_code(obj, comment = FALSE, highlight = "r", ...)
An object to be printed and returned as strings.
Either logical or a string:
If TRUE
- default knitr
chunk of code comment symbols are
used (usually ##
).
If FALSE
(default) or NA
- no comment is used.
If a string, the entered symbols are used as comment symbols.
Either NULL
, FALSE
or a string with name of
programming language for which rules of
code highlighting will be applied. Default is "r".
Further arguments to be passed to print
.
A vector of strings.
Function prints the object obj
(see print
),
captures the output (see capture.output
),
adds comment
at the beggining of each string and
adds \`\`\`
+ value of highlight
as the first string
(e.g., \`\`\`r
) and
\`\`\`
as the last string (see section "Examples").
format_as_code(summary(cars))
#> [1] "```r" " speed dist "
#> [3] " Min. : 4.0 Min. : 2.00 " " 1st Qu.:12.0 1st Qu.: 26.00 "
#> [5] " Median :15.0 Median : 36.00 " " Mean :15.4 Mean : 42.98 "
#> [7] " 3rd Qu.:19.0 3rd Qu.: 56.00 " " Max. :25.0 Max. :120.00 "
#> [9] "```"
#> [1] "```r"
#> [2] " speed dist "
#> [3] " Min. : 4.0 Min. : 2.00 "
#> [4] " 1st Qu.:12.0 1st Qu.: 26.00 "
#> [5] " Median :15.0 Median : 36.00 "
#> [6] " Mean :15.4 Mean : 42.98 "
#> [7] " 3rd Qu.:19.0 3rd Qu.: 56.00 "
#> [8] " Max. :25.0 Max. :120.00 "
#> [9] "```"
# Set parameter `comment = TRUE`
format_as_code(summary(cars), comment = TRUE)
#> [1] "```r" "## speed dist "
#> [3] "## Min. : 4.0 Min. : 2.00 " "## 1st Qu.:12.0 1st Qu.: 26.00 "
#> [5] "## Median :15.0 Median : 36.00 " "## Mean :15.4 Mean : 42.98 "
#> [7] "## 3rd Qu.:19.0 3rd Qu.: 56.00 " "## Max. :25.0 Max. :120.00 "
#> [9] "```"
#> [1] "```r"
#> [2] "## speed dist "
#> [3] "## Min. : 4.0 Min. : 2.00 "
#> [4] "## 1st Qu.:12.0 1st Qu.: 26.00 "
#> [5] "## Median :15.0 Median : 36.00 "
#> [6] "## Mean :15.4 Mean : 42.98 "
#> [7] "## 3rd Qu.:19.0 3rd Qu.: 56.00 "
#> [8] "## Max. :25.0 Max. :120.00 "
#> [9] "```"
# Compare the lines above to:
summary(cars)
#> 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
#> 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
format_as_code("a")
#> [1] "```r" " [1] \"a\"" "```"
#> [1] "```r"
#> [2] " [1] \"a\""
#> [3] "```"