Skip to contents

To extract code blocks, apply extract_code() to R Markdown or Quarto files either locally or via a URL. This function returns a character vector where each line of content from an R code block is an element of the vector. Code block options are not returned—only the content of the block. Code blocks from other languages/engines (e.g., Python) are not returned.

Usage

extract_code(file, empty = TRUE, comments = TRUE)

Arguments

file

Character string of file name for text that includes code blocks. Can be local file or URL.

empty

Logical indicating whether to include empty lines ("") or whether to remove empty lines (default is TRUE, which includes empty lines).

comments

Logical indicating whether to include comment lines starting with # or whether to remove comment lines (default is TRUE, which includes comment lines).

Value

Returns character vector of individual lines of code.

Note

This function is adapted from one Yihui Xie posted at https://yihui.org/en/2023/01/func-call/.

See also

Other functions for extracting code and functions: build_functions_df(), extract_functions()

Examples

extract_code("https://raw.githubusercontent.com/JeffreyRStevens/flashr/refs/heads/main/README.Rmd")
#>  [1] "knitr::opts_chunk$set("                             
#>  [2] "  collapse = TRUE,"                                 
#>  [3] "  comment = \"#>\","                                
#>  [4] "  fig.path = \"man/figures/README-\","              
#>  [5] "  out.width = \"100%\""                             
#>  [6] ")"                                                  
#>  [7] "install.packages(\"flashr\")"                       
#>  [8] "# install.packages(\"remotes\")"                    
#>  [9] "remotes::install_github(\"JeffreyRStevens/flashr\")"
#> [10] "library(flashr)"                                    
#> [11] "flashcard(\"data_types\")"                          
#> [12] "flashcard(\"data_types\", termsfirst = FALSE)"      
#> [13] "my_deck <- read.csv(\"inst/extdata/operators.csv\")"
#> [14] ""                                                   
#> [15] "head(my_deck)"                                      
#> [16] "flashcard(\"inst/extdata/operators.csv\")"