R语言中创建支持可选引号的二元运算符%&%的实现问题
Solution for R's %&% Binary Operator
To create a binary operator %&% that concatenates two strings with a space—whether the inputs are quoted or unquoted—we need to use non-standard evaluation (NSE) to capture the literal text of each argument, regardless of whether it's wrapped in quotes.
Step-by-Step Implementation:
- Capture unevaluated arguments: Use
substitute()to get the raw expression of each input (this preserves both quoted strings and unquoted symbols). - Convert to character: Use
as.character()to turn both symbols and quoted strings into plain text strings. - Concatenate with space: Use
paste()to combine the two strings with a single space separator.
Final Code:
`%&%` <- function(a, b) { # Capture the literal input text for each argument a_text <- as.character(substitute(a)) b_text <- as.character(substitute(b)) # Concatenate with a space paste(a_text, b_text) }
Testing the Operator:
Let's verify it works for both quoted and unquoted inputs:
# Unquoted arguments Hello %&% World # Output: [1] "Hello World" # Quoted arguments "Hello" %&% "World" # Output: [1] "Hello World" # Mixed quoted/unquoted Hi %&% "there" # Output: [1] "Hi there"
Key Notes:
- This operator treats unquoted inputs as literal text, not variable names. Even if you don't have a variable named
Hello,Hello %&% Worldwill still return"Hello World". - If you pass a variable (e.g.,
x <- "Hi"; x %&% World), it will use the variable's name ("x") instead of its value. This aligns with your requirement of treating quotes as optional for literal string inputs.
内容的提问来源于stack exchange,提问作者dataminingblues
相关产品推荐
相关产品推荐

