What are the caveats of using source versus parse & eval?

后端 未结 1 511
清歌不尽
清歌不尽 2020-12-14 14:35

Short version

Can I replace

source(filename, local = TRUE, encoding = \'UTF-8\')

with

eval(parse(filename, encodi         


        
1条回答
  •  囚心锁ツ
    2020-12-14 14:49

    This is not a full answer as it primarily addresses the seq_along part of the question, but too lengthy to include as comments.

    One key difference between the seq_along followed by [ vs just using for i in x approach (which I believe is be similar to seq_along followed by [[ instead of [) is that the former preserves the expression. Here is an example to illustrate the difference:

    > txt <- "x <- 1 + 1
    + # abnormal expression
    +   2 *
    +     3
    + "
    > x <- parse(text=txt, keep.source=TRUE)
    > 
    > for(i in x) print(i)
    x <- 1 + 1
    2 * 3
    > for(i in seq_along(x)) print(x[i])
    expression(x <- 1 + 1)
    expression(2 *
        3)
    

    Alternatively:

    > attributes(x[[2]])
    NULL
    > attributes(x[2])
    $srcref
    $srcref[[1]]
    2 *
        3
    

    Whether this has any practical impact when comparing to eval(parse(..., keep.source=T)), I can only say that it could, but can't imagine a situation where it does.

    Note that subsetting expression separately also leads to the srcref business getting subset, which could conceivably be useful (...maybe?).

    0 讨论(0)
提交回复
热议问题