Home > Custom Function > A handy concatenation operator

A handy concatenation operator

It may be useful for you to define a concatenation operator for characters. Sometimes, I find this is more intuitive and handy than using paste0 or paste. Also, it makes your code look better when you have nested paste, e.g.paste0("Y~",paste0("z",1:3, "*x",1:3,collapse="+"). The drawback is that it may reduce the readability of your code to other R user, since it is a self define function.(i guess it should be fine, cuz it is really intuitive. Also other scripting language also has similar concatenation operator)

"%+%" <- function(...){
> "hello" %+% "world"
[1] "helloworld"
"hello" %+% "world" %+% 1:3
[1] "helloworld1" "helloworld2" "helloworld3"

Generating formula:

"Y~" %+% paste0("z",1:3, "*x",1:3,collapse="+")
[1] "Y~z1*x1+z2*x2+z3*x3"
About these ads
Categories: Custom Function
  1. Georgii
    February 13, 2013 at 07:18

    It should in R core I think

    • February 13, 2013 at 20:11

      Indeed. Actually if R core has similar function, i hope they will use + instead %+%.

  2. No One
    February 13, 2013 at 17:36

    why paste0 instead of paste?

    • February 13, 2013 at 20:09

      you can do the same thing with paste0 is paste with sep=””. paste0 and paste would be the same in this case.

  1. February 12, 2013 at 16:27

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: