format_as_code: Format object to be printed as a code in a Markdown file

View source: R/format_as_code.R

format_as_codeR Documentation

Format object to be printed as a code in a Markdown file

Description

Function prints object, captures the output and formats it so that it will be printed as a piece of code in a Markdown file.

Usage

format_as_code(obj, comment = FALSE, highlight = "r", ...)

Arguments

obj

An object to be printed and returned as strings.

comment

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.

highlight

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.

Details

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").

Value

A vector of strings.

Examples


format_as_code(summary(cars))
 #> [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"
 #> [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


format_as_code("a")
 #> [1] "```r"
 #> [2] " [1] \"a\""
 #> [3] "```"


GegznaV/knitrContainer documentation built on April 16, 2023, 1:38 p.m.