Skip to contents

This function takes an R script containing traditional (nested syntax) R code and converts it to magrittr-style syntax, using the pipe ( It also validates the input and output code to ensure proper R syntax.


nested_to_pipe(r, n_tokens_limit = 3000, ...)



A file path or character string containing the R code to be converted.


The maximum number of tokens allowed in the input text (default: 3000).


Additional arguments to pass to the chat_completion() function.


If r is a character string, the function returns the converted R code as a character string. If r is a file path, the function writes the converted code to a new file with the same name and a "-pipe.R" suffix, and returns the path to the output file.


if (FALSE) {
# Converting a character string
input <- "result <- mean(sqrt(abs(rnorm(10, 0, 1))), na.rm = TRUE)"
output <- nested_to_pipe(input)

# Converting a file
# Create a temporary input file
input_file <- tempfile(fileext = ".R")
write("result <- mean(sqrt(abs(rnorm(10, 0, 1))), na.rm = TRUE)", input_file)

# Convert the file using nested_to_pipe
output_file <- nested_to_pipe(input_file)

# Check the converted file content