在R中创建字符串连接运算符

Hon*_*Ooi 43 string r string-concatenation

我想知道如何在R中编写字符串连接运算符,类似于|| 在SAS中,在Java/C#中使用+或在Visual Basic中使用&.

最简单的方法是使用%创建一个特殊的运算符

`%+%` <- function(a, b) paste(a, b, sep="")
Run Code Online (Sandbox Code Playgroud)

但这会导致%代码中出现许多难看的东西.

我注意到这+是在Ops组中定义的,你可以为该组编写S4方法,所以也许这样的方法就可以了.但是,我根本没有使用S4语言功能的经验.如何修改上述功能才能使用S4?

小智 41

正如其他人所提到的,你无法覆盖密封的S4方法"+".但是,您不需要定义新类以便为字符串定义添加函数; 这并不理想,因为它迫使你转换字符串类,从而导致更丑陋的代码.相反,人们可以简单地覆盖"+"函数:

"+" = function(x,y) {
    if(is.character(x) || is.character(y)) {
        return(paste(x , y, sep=""))
    } else {
        .Primitive("+")(x,y)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后以下应该按预期工作:

1 + 4
1:10 + 4 
"Help" + "Me"
Run Code Online (Sandbox Code Playgroud)

这个解决方案感觉有点像黑客,因为你不再使用正式的方法,但它是获得你想要的确切行为的唯一方法.

  • 它不会破坏我的ggplot2.ggplot2将其"+"定义为类"gg"的S3方法.参见`?ggplot2 ::`%+%``. (6认同)
  • 我对S3/4并不熟悉 - 这究竟是什么hacky?似乎工作得很好. (3认同)

jve*_*ani 22

您还可以使用S3类:

String <- function(x) {
  class(x) <- c("String", class(x))
  x
}

"+.String" <- function(x,...) {
  x <- paste(x, paste(..., sep="", collapse=""), sep="", collapse="")
  String(x)
}


print.String <- function(x, ...) cat(x)

x <- "The quick brown "
y <- "fox jumped over "
z <- "the lazy dog"

String(x) + y + z
Run Code Online (Sandbox Code Playgroud)


Lyt*_*tze 22

我会试试这个(相对更干净的S3解决方案)

`+` <- function (e1, e2) UseMethod("+")
`+.default` <- function (e1, e2) .Primitive("+")(e1, e2)
`+.character` <- function(e1, e2) 
    if(length(e1) == length(e2)) {
           paste(e1, e2, sep = '')
    } else stop('String Vectors of Different Lengths')
Run Code Online (Sandbox Code Playgroud)

上面的代码将更改+到一个通用的,并设置+.default到原来的+,再加入新的方法+.character来+


Vit*_*hKa 11

如果R可以完全遵守S4,那么下面就足够了:

setMethod("+",
          signature(e1 = "character", e2 = "character"),
          function (e1, e2) {
              paste(e1, e2, sep = "")
      })
Run Code Online (Sandbox Code Playgroud)

但是这给出了一个错误,即该方法是密封的:((.希望这会在R的特征版本中发生变化.

你能做的最好的事情是定义新的类"string",它的行为与"character"类完全相同:

setClass("string", contains="character")
string <- function(obj) new("string", as.character(obj))
Run Code Online (Sandbox Code Playgroud)

并定义R允许的最通用的方法:

setMethod("+", signature(e1 = "character", e2 = "ANY"),
          function (e1, e2) string(paste(e1, as.character(e2), sep = "")))
Run Code Online (Sandbox Code Playgroud)

现在尝试:

tt <- string(44444)

tt
#An object of class "string"
#[1] "44444"
tt + 3434
#[1] "444443434"
"sfds" + tt
#[1] "sfds44444"
tt +  tt
#[1] "4444444444"
343 + tt
#Error in 343 + tt : non-numeric argument to binary operator
"sdfs" + tt + "dfsd"
#An object of class "string"
#[1] "sdfs44444dfsd"
Run Code Online (Sandbox Code Playgroud)


Dir*_*tel 8

你给了自己正确的答案 - R中的所有东西都是一个函数,你无法定义新的运算符.所以%+%尽可能好.

  • 但您可以重新定义现有运营商的行为.不是在这种情况下,因为"+"方法是为签名c("字符","字符")密封的. (3认同)