Evaluate R code by chunks, then insert the output to each chunk. As the output is masked in comments, the source code will not break.

tidy_eval(
  source = "clipboard",
  ...,
  file = "",
  prefix = "## ",
  envir = parent.frame()
)

Arguments

source

The input file name (by default the clipboard; see tidy_source()).

...

Other arguments passed to tidy_source().

file

The file name to write to via cat().

prefix

The prefix to mask the output.

envir

The environment in which to evaluate the code. By default the parent frame; set envir = NULL or envir = new.env() to avoid the possibility of contaminating the parent frame.

Value

Evaluated R code with corresponding output (printed on screen or written to a file).

Examples

library(formatR)
## evaluate simple code as a character vector
tidy_eval(text = c("a<-1+1;a", "matrix(rnorm(10),5)"))
#> a <- 1 + 1
#> a
#> ## [1] 2
#> 
#> matrix(rnorm(10), 5)
#> ##              [,1]       [,2]
#> ## [1,] -0.005571287 -0.2441996
#> ## [2,]  0.621552721 -0.2827054
#> ## [3,]  1.148411606 -0.5536994
#> ## [4,] -1.821817661  0.6289820
#> ## [5,] -0.247325302  2.0650249
#> 

## evaluate a file
tidy_eval(system.file("format", "messy.R", package = "formatR"))
#> # a single line of comments is preserved
#> 1 + 1
#> ## [1] 2
#> 
#> 
#> if (TRUE) {
#>     x = 1  # inline comments
#> } else {
#>     x = 2
#>     print("Oh no... ask the right bracket to go away!")
#> }
#> 1 * 3  # one space before this comment will become two!
#> ## [1] 3
#> 
#> 2 + 2 + 2  # 'short comments'
#> ## [1] 6
#> 
#> 
#> # only 'single quotes' are allowed in comments
#> df = data.frame(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100))
#> lm(y ~ x1 + x2, data = df)
#> ## 
#> ## Call:
#> ## lm(formula = y ~ x1 + x2, data = df)
#> ## 
#> ## Coefficients:
#> ## (Intercept)           x1           x2  
#> ##     0.02066      0.02910      0.05023  
#> ## 
#> 
#> 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
#>     1 + 1  ## comments after a long line
#> ## [1] 23
#> 
#> 
#> ## here is a long long long long long long long long long long long long long
#> ## long long long long long long long comment