Examples for 'base::parse'


Parse R Expressions

Aliases: parse str2lang str2expression

Keywords: file programming connection

### ** Examples

fil <- tempfile(fileext = ".Rdmped")
cat("x <- c(1, 4)\n  x ^ 3 -10 ; outer(1:7, 5:9)\n", file = fil)
# parse 3 statements from our temp file
parse(file = fil, n = 3)
expression(x <- c(1, 4), x ^ 3 -10, outer(1:7, 5:9))
unlink(fil)

## str2lang(<string>)  || str2expression(<character>) :
stopifnot(exprs = {
  identical( str2lang("x[3] <- 1+4"), quote(x[3] <- 1+4))
  identical( str2lang("log(y)"),      quote(log(y)) )
  identical( str2lang("abc"   ),      quote(abc) -> qa)
  is.symbol(qa) & !is.call(qa)           # a symbol/name, not a call
  identical( str2lang("1.375" ), 1.375)  # just a number, not a call
  identical( str2expression(c("# a comment", "", "42")), expression(42) )
})

# A partial parse with a syntax error
txt <- "
x <- 1
an error
"
sf <- srcfile("txt")
try(parse(text = txt, srcfile = sf))
Error in parse(text = txt, srcfile = sf) : txt:3:4: unexpected symbol
2: x <- 1
3: an error
      ^
getParseData(sf)
   line1 col1 line2 col2 id parent       token terminal  text
9      2    1     2    6  9      0        expr    FALSE      
3      2    1     2    1  3      5      SYMBOL     TRUE     x
5      2    1     2    1  5      9        expr    FALSE      
4      2    3     2    4  4      9 LEFT_ASSIGN     TRUE    <-
6      2    6     2    6  6      7   NUM_CONST     TRUE     1
7      2    6     2    6  7      9        expr    FALSE      
12     3    1     3    2 12     14      SYMBOL     TRUE    an
14     3    1     3    2 14      0        expr    FALSE      
13     3    4     3    8 13      0      SYMBOL     TRUE error

[Package base version 4.2.3 Index]