R 中的操作重载
重载字符“+”的最直接方法是什么? 我已经定义了 '%+%' <- function(...) Paste(...,sep="")
:
str <- "aa"%+%"bb"%+%"cc" #str="aabbcc"
但我不喜欢这种语法。我认为 str <- "aa"+"bb"+"cc"
会更好。
(我正在构建长 SQL 查询以与 RODBC 一起使用,通常的 paste
在这种情况下不太方便。有什么建议吗?)
What's the most straight forward way of overloading '+' for characters?
I have defined '%+%' <- function(...) paste(...,sep="")
:
str <- "aa"%+%"bb"%+%"cc" #str="aabbcc"
But I don't like the syntax. I think str <- "aa"+"bb"+"cc"
would be nicer.
(I am building long SQL queries to use with RODBC, the usual paste
is not very handy in such situations. Any suggestions?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以尝试这样的事情:
这给出了:
但正如 Sacha 指出的,重载这样一个基本函数是非常危险的,我不能向你保证它不会破坏你的 R 会话并使你的计算机爆炸:-)
You may try something like that :
Which gives :
But as Sacha pointed out, overloading such a basic function is very dangerous, and I can't assure you it will not break your R session and make your computer explode :-)
我认为使用两个参数比点更好:
如果你真的想要,你可以覆盖
+
,但这样做时要非常小心,因为你会破坏 R 中最重要的函数之一。我想不出你想要在%+%
上这样做的任何原因:将其注释掉以确保我不会意外地破坏某人 R:)
I think that using two arguments is better than the dots:
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%+%
:commented it out to be sure I don't accidently break someones R:)
为什么通常的“粘贴”不太方便?这就是它的目的。建议:
自己编写一个不寻常的粘贴函数来完成您想要的操作。也许您只是不喜欢一直输入“sep="”'。因此编写一个使用 sep="" 调用 Paste 的函数。或者无论如何。
无论如何,使用字符串连接构建长 SQL 查询都可能会失败。请参阅 http://xkcd.com/327/ 了解规范示例。
另一种可能性是某种模板解决方案。我过去使用过brew 包,它非常适合。
Why is the usual 'paste' not very handy? It's what it's meant for. Suggestions:
Write yourself an unusual paste function that does what you want. Maybe you just don't like typing 'sep=""' all the time. So write a function that calls paste with sep="". Or whatever.
Building long SQL queries with string concatenation is potential fail anyway. See http://xkcd.com/327/ for the canonical example.
Another possibility is some kind of templating solution. I've used the brew package in the past and it's great for that.
您可以在
stringi
包中找到该运算符。http://docs.rexamine.com/R-man/stringi/oper_plus.html
You can find this operator in
stringi
package.http://docs.rexamine.com/R-man/stringi/oper_plus.html