Learn R Programming

llmflow (version 3.0.2)

extract_r_code: Extract R code from a string

Description

This function extracts R code from a string by matching all content between '```r' or '```R' and '```'.

Usage

extract_r_code(input_string)

Value

A character vector containing the extracted R code

Arguments

input_string

A string containing R code blocks, typically a response from an LLM

Examples

Run this code
# Simple example
text <- "Here is some R code:\n```r\nprint('Hello')\n```"
extract_r_code(text)

# Multiple code blocks
response <- "
First block:
```r
x <- 1:10
mean(x)
```

Second block:
```R
library(ggplot2)
ggplot(mtcars, aes(mpg, hp)) + geom_point()
```
"
codes <- extract_r_code(response)
length(codes) # Returns 2

# With surrounding text
llm_response <- "
To calculate the mean, use this code:
```r
data <- c(1, 2, 3, 4, 5)
result <- mean(data)
print(result)
```
The result will be 3.
"
extract_r_code(llm_response)

Run the code above in your browser using DataLab