在 R 中制作字符串连接运算符 [英] Making a string concatenation operator in R

查看:47
本文介绍了在 R 中制作字符串连接运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

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

The easiest way would be to create a special operator using %, like

`%+%` <- function(a, b) paste(a, b, sep="")

但这会导致代码中出现很多丑陋的%.

but this leads to lots of ugly %'s in the code.

我注意到 + 是在 Ops 组中定义的,您可以为该组编写 S4 方法,因此也许类似的方法是可行的方法.但是,我完全没有使用 S4 语言功能的经验.我将如何修改上述功能以使用 S4?

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?

推荐答案

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

As others have mentioned, you cannot override the sealed S4 method "+". However, you do not need to define a new class in order to define an addition function for strings; this is not ideal since it forces you to convert the class of strings and thus leading to more ugly code. Instead, one can simply overwrite the "+" function:

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

那么以下内容都应该按预期工作:

Then the following should all work as expected:

1 + 4
1:10 + 4 
"Help" + "Me"

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

This solution feels a bit like a hack, since you are no longer using formal methods but its the only way to get the exact behavior you wanted.

这篇关于在 R 中制作字符串连接运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆