Skip to contents

This function checks whether a character string is syntactically valid R code. It only parses the code with base::parse(); it never evaluates it, so checking code has no side effects. Code that parses but would fail at run time (e.g., x <- 5 + 'a' or library(notapkg)) counts as valid.

Usage

is_r(code)

Arguments

code

A character string containing the R code to be checked. A character vector with more than one element is treated as the lines of one script (one element per line). Windows (CRLF) line endings are accepted.

Value

A single TRUE if code parses as R code, FALSE otherwise. Non-character input, NA elements and empty or blank strings return FALSE.

Examples

# Valid R code
valid_code <- "x <- 5; y <- 10; z <- x + y"
is_r(valid_code)
#> [1] TRUE

# Invalid R code (unbalanced parenthesis)
invalid_code <- "x <- (5 + 1"
is_r(invalid_code)
#> [1] FALSE

# The code is parsed, not run: this does not create a file
is_r("file.create('never_created.txt')")
#> [1] TRUE