R中的操作超载 [英] Operation overloading in R

查看:67
本文介绍了R中的操作超载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为字符重载 +的最直接方法是什么?
我已经定义了'%+%'<-function(...)paste(...,sep =)

What's the most straight forward way of overloading '+' for characters? I have defined '%+%' <- function(...) paste(...,sep=""):

str <- "aa"%+%"bb"%+%"cc" #str="aabbcc"

但是我不喜欢这种语法。我认为 str<- aa + bb + cc 会更好。

But I don't like the syntax. I think str <- "aa"+"bb"+"cc" would be nicer.

(我正在构建用于RODBC的长SQL查询,通常的 paste 在这种情况下不是很方便。有什么建议吗?)

(I am building long SQL queries to use with RODBC, the usual paste is not very handy in such situations. Any suggestions?)

推荐答案

我认为使用两个参数比点更好:

I think that using two arguments is better than the dots:

'%+%' <- function(x,y) paste(x,y,sep="")

"a"%+%"b"%+%"C"
[1] "abC"

如果您确实要覆盖 + ,但是在执行此操作时要小心,因为这样会破坏R中最重要的功能之一。我可以没想到您为什么要超过%+%

If you really really want to you can overwrite +, but be veeeeery careful when doing this as you will break one of the most important functions in R. I can't think of any reason why you would want to do that over %+%:

# '+' <- function(x,y) paste(x,y,sep="")
# "a"+"b"+"C"
# [1] "abC"

rm('+')

对此发表了评论确保我不会意外破坏某人R:)

commented it out to be sure I don't accidently break someones R:)

这篇关于R中的操作超载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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