rlang包中sym()与parse_expr()的区别及差异原因咨询
sym() and parse_expr() in rlang Let's break down why you're seeing different results when using sym() vs parse_expr() with expressions like 'a - b', even though they behave identically for single symbols.
1. Single symbols: They work the same
When you pass a simple variable name string like 'a':
sym('a')directly creates a symbol object (a representation of a variable name).parse_expr('a')parses the string as an expression, which for a single token also resolves to a symbol object.
This is why identical(sym('a'), parse_expr('a')) returns TRUE—they're the exact same type of object pointing to the same variable. This consistency carries over when unquoting into a quosure with !!, since both resolve to the same symbol inside the quosure environment.
2. Compound expressions: The critical difference
The split happens when you pass a string that represents an operation (like 'a - b'):
sym('a - b')treats the entire string as one single, literal symbol. It doesn't interpret the subtraction—it just creates a variable name that includes spaces and a minus sign (R allows these "non-standard" variable names if you wrap them in backticks, e.g.,`a - b`).parse_expr('a - b')actually parses the string into a call expression: it recognizes the subtraction operator and builds an object representing the operation of subtractingbfroma.
Let's use code to see the structural difference clearly:
library(rlang) # Inspect the raw objects str(sym('a - b')) #> symbol a - b str(parse_expr('a - b')) #> language a - b # Inspect the quosures ex5 <- quo(!!sym('a - b')) ex6 <- quo(!!parse_expr('a - b')) str(ex5) #> quosure #> expr: ^`a - b` #> env: global str(ex6) #> quosure #> expr: ^a - b #> env: global
You can see ex5 holds a single quoted symbol `a - b` (a weirdly named variable), while ex6 holds the actual arithmetic expression a - b. That's why identical(ex5, ex6) returns FALSE—they're fundamentally different types of expressions.
3. Quick rule of thumb for usage
- Use
sym()when you need to reference a single variable by its name string (e.g., dynamically selecting a data frame column). - Use
parse_expr()when you need to turn a full expression string into executable R code (like arithmetic, function calls, or complex logic).
内容的提问来源于stack exchange,提问作者Rtist

