You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Capture unevaluated arguments: Use substitute() to get the raw expression of each input (this preserves both quoted strings and unquoted symbols).
  2. Convert to character: Use as.character() to turn both symbols and quoted strings into plain text strings.
  3. 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 %&% World will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:17:43