首页 > 解决方案 > `getParseData` 在 `interactive()` 与 Rscript 中产生不同的结果

问题描述

请参阅下面的 MWE

generate_summ_code= function(...) {
  code = substitute(list(...))[-1]
  gpd = getParseData(parse(text = deparse(code)), includeText = TRUE)
  print(gpd)
  gpd
}

generate_summ_code(n = n())

如果我在 REPL 中运行它,我会打印出来

>    line1 col1 line2 col2 id parent                token terminal  text
> 10     1    1     1    5 10      0                 expr    FALSE n()()
> 6      1    1     1    3  6     10                 expr    FALSE   n()
> 1      1    1     1    1  1      3 SYMBOL_FUNCTION_CALL     TRUE     n
> 3      1    1     1    1  3      6                 expr    FALSE     n
> 2      1    2     1    2  2      6                  '('     TRUE     (
> 4      1    3     1    3  4      6                  ')'     TRUE     )
> 7      1    4     1    4  7     10                  '('     TRUE     (
> 8      1    5     1    5  8     10                  ')'     TRUE     )

但是,如果我将代码放在文件中code.r,我会说

Rscript code.r

或者

R -e "source('code.r')"

它只返回 NULL。中没有任何内容?getParseData表明行为应该有所不同?

这是 Base R 中的错​​误吗?

标签: rnse

解决方案


不同之处在于,在交互模式下,该keep.source选项设置为TRUE,否则设置为FALSE(除非您覆盖它)。因此,parse不同的行为:

〉getParseData(parse(text = '1 + 1'), includeText = TRUE)
  line1 col1 line2 col2 id parent     token terminal  text
7     1    1     1    5  7      0      expr    FALSE 1 + 1
1     1    1     1    1  1      2 NUM_CONST     TRUE     1
2     1    1     1    1  2      7      expr    FALSE     1
3     1    3     1    3  3      7       '+'     TRUE     +
4     1    5     1    5  4      5 NUM_CONST     TRUE     1
5     1    5     1    5  5      7      expr    FALSE     1
〉getParseData(parse(text = '1 + 1', keep.source = FALSE), includeText = TRUE)
NULL

推荐阅读