1. Introduction

介绍两个名词:

  • The quosure: a data structure that captures an expression along with its associated environment, as found in function arguments.(一个数据结构?类似于list?就是说捕获表达式的同时还可以捕获他的环境)
  • The data mask, which makes it easier to evaluate an expression in the context of a data frame. This introduces potential evaluation ambiguity which we’ll then resolve with data pronouns.

Together, quasiquotation, quosures, and data masks form what we call tidy evaluation

Outline

  • Section 20.2 discusses the basics of evaluation using eval(), and shows how you can use it to implement key functions like local() and source().
  • Section 20.3 introduces a new data structure, the quosure, which combines an expression with an environment. You’ll learn how to capture quosures from promises, and evaluate them using rlang::eval_tidy().
  • Section 20.4 extends evaluation with the data mask, which makes it trivial to intermingle symbols bound in an environment with variables found in a data frame.
  • Section 20.5 shows how to use tidy evaluation in practice, focussing on the common pattern of quoting and unquoting, and how to handle ambiguity with pronouns.
  • Section 20.6 circles back to evaluation in base R, discusses some of the downsides, and shows how to use quasiquotation and evaluation to wrap functions that use NSE.

    2. Evaluation basics

    eval,有两个重要的参数,一个是expr,一个是envir ```r x <- 10 eval(expr(x)) # symbols

    > [1] 10

y <- 2 eval(expr(x + y)) # expressions

> [1] 12

eval(print(x + 1), env(x = 1000))

> [1] 11

> [1] 11

eval(expr(print(x + 1)), env(x = 1000))

> [1] 1001

  1. <a name="Em7LA"></a>
  2. ### 2.1 Application: local()
  3. 有时候你一系列的计算中会产生很多中间变量,这些中间变量往往只用一次,很是无用。因此这时可以使用local
  4. ```r
  5. # Clean up variables created earlier
  6. rm(x, y)
  7. foo <- local({
  8. x <- 10
  9. y <- 200
  10. x + y
  11. })
  12. foo
  13. #> [1] 210
  14. x
  15. #> Error in eval(expr, envir, enclos): object 'x' not found
  16. y
  17. #> Error in eval(expr, envir, enclos): object 'y' not found

2.2 Application: source()

We read in the file from disk, use parse_expr() to parse the string into a list of expressions, and then use eval() to evaluate each element in turn.

source():Read R Code from a File, a Connection or Expressions