<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/adding-strings-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://jcarroll.com.au/2018/10/06/adding-strings-in-r/"> R – Irregularly Scheduled Programming</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This started out as a <i>“hey, I wonder…”</i> sort of thing, but as usual, they tend to end up as interesting voyages into the deepest depths of code, so I thought I’d write it up and share. Shoutout to <a rel="nofollow" href="https://twitter.com/coolbutuseless" target="_blank">@coolbutuseless</a> for proving that a little curiosity can go a long way and inspiring me to keep digging into interesting topics.</p>
<p><div class="wp-caption"><img src="https://i2.wp.com/jcarroll.com.au/wp-content/uploads/2018/10/stringeastereggs.jpg?resize=680%2C451&ssl=1" alt="This is what you get if you " data-recalc-dims="1">
<p class="wp-caption-text">This is what you get if you &quot;glue&quot; &quot;strings&quot;. Photo: https://craftwhack.com/cool-craft-string-easter-eggs/</p>
</div>
<p><span></span></p>
<p><a rel="nofollow" href="http://www.happylittlescripts.com/2018/09/make-your-r-code-nicer-with-roperators.html" target="_blank">This post</a> came across my feed last week, referring to the <a rel="nofollow" href="https://cran.r-project.org/package=roperators" target="_blank">roperators package on CRAN</a>. In that post, the author introduces an infix operator from that package which ‘adds’ (concatenates/pastes) strings</p>
<pre>
&quot;using infix (%) operators&quot; %+% &quot;R can do simple string addition&quot;
#> [1] &quot;using infix (%) operators R can do simple string addition&quot;
</pre>
<p>This might be familiar if you use python</p>
<pre>
>>> &quot;python &quot; + &quot;adds &quot; + &quot;strings&quot;
'python adds strings'
</pre>
<p>or javascript</p>
<pre>
&quot;javascript &quot; + &quot;also adds &quot; + &quot;strings&quot;
&quot;javascript also adds strings&quot;
</pre>
<p>or perhaps even go</p>
<pre>
package main

import &quot;fmt&quot;

func main() {
  fmt.Println(&quot;go &quot; + &quot;even adds &quot; + &quot;strings&quot;)
}
> &quot;go even adds strings&quot;
</pre>
<p>but this is not something natively available in R</p>
<pre>
&quot;this doesn't&quot; + &quot;work&quot;
#> Error in &quot;this doesn't&quot; + &quot;work&quot; : 
#>  non-numeric argument to binary operator
</pre>
<p><img src="https://i2.wp.com/jcarroll.com.au/wp-content/uploads/2018/10/nazi.jpg?resize=240%2C300&ssl=1" data-recalc-dims="1"></p>
<p>Could we make it work, though? That got me wondering. My first guess was to just create a new <code>+</code> function which <i>does</i> allow for this. The normal addition operator is</p>
<pre>
`+`
#> function (e1, e2)  .Primitive(&quot;+&quot;)
</pre>
<p>so a first attempt might be</p>
<pre>
`+` &lt;- function(e1, e2) {
  if (is.character(e1) | is.character(e2)) {
    paste0(e1, e2)
  } else {
    base::`+`(e1, e2)
  }
}
</pre>
<p>This checks to see if the left or right side of the operator is a character-classed object, and if either is, it pastes the two together. Otherwise it just uses the ‘regular’ addition operator between the two arguments. This works for simple cases, e.g.</p>
<pre>
&quot;a&quot; + &quot;b&quot;
#> [1] &quot;ab&quot;

&quot;a&quot; + 2
#> [1] &quot;a2&quot;

2 + 2
#> [1] 4

2 + &quot;a&quot;
#> [1] &quot;2a&quot;
</pre>
<p>But we hit an important snag if we try to add to character-represented numbers</p>
<pre>
&quot;200&quot; + &quot;200&quot;
#> [1] &quot;200200&quot;
</pre>
<p>That’s probably going to be an issue if we read in unformatted data (e.g. from a CSV) as characters and try to treat it like numbers. Normally this would throw the above error about not being numeric, but now we get a silent weird number-character. That’s no good.</p>
<p>An extension to this checks whether or not we have the number-as-a-character situation and falls back to the correct interpretation in that case</p>
<pre>
`+` &lt;- function(e1, e2) {
  ## unary
  if (missing(e2)) return(e1)
  if (!is.na(suppressWarnings(as.numeric(e1))) &amp; !is.na(suppressWarnings(as.numeric(e2)))) {
    ## both arguments numeric-like but characters
    return(base::`+`(as.numeric(e1), as.numeric(e2)))
  } else if ((is.character(e1) &amp; is.na(suppressWarnings(as.numeric(e1)))) | 
             (is.character(e2) &amp; is.na(suppressWarnings(as.numeric(e2))))) {
    ## at least one true character 
    return(paste0(e1, e2))
  } else {
    ## both numeric
    return(base::`+`(e1, e2))
  }
}

&quot;a&quot; + &quot;b&quot;
#> [1] &quot;ab&quot;

&quot;a&quot; + 2
#> [1] &quot;a2&quot;

2 + 2
#> [1] 4

2 + &quot;a&quot;
#> [1] &quot;2a&quot;

&quot;2&quot; + &quot;2&quot;
#> [1] 4

2 + &quot;edgy&quot; + 4 + &quot;me&quot;
#> [1] &quot;2edgy4me&quot;
</pre>
<p>So, that’s one option for string addition in R. Is it the right one? The idea of actually dispatching on a character class is inviting. Can we just add a <code>+.character</code> method (since there doesn’t seem to already be one)? Normally when we have S3 dispatch we need a generic function, which calls <code>UseMethod(&quot;class&quot;)</code>, but we don’t have that in this case. <code>+</code> is an internal generic, which is probably the first sign that we’re going to have trouble. If we try to define the method</p>
<pre>
`+.character` &lt;- function(e1, e2) {
  paste0(e1, e2)
}
&quot;a&quot; + &quot;b&quot;
#> Error in &quot;a&quot; + &quot;b&quot; : non-numeric argument to binary operator
</pre>
<p>It seems to fail. What went wrong? Is dispatch not working? </p>
<p><iframe width="450" allowfullscreen src="https://giphy.com/embed/dbtDDSvWErdf2"></iframe></p>
<p><a rel="nofollow" href="https://giphy.com/gifs/richard-ayoade-it-crowd-maurice-moss-dbtDDSvWErdf2" target="_blank">via GIPHY</a></p>
<p>We want to dispatch on “character” — is that what we have?</p>
<pre>
class(&quot;a&quot;)
#> [1] &quot;character&quot;
</pre>
<p>What if we explicitly create an object with that class?</p>
<pre>
structure(&quot;a&quot;, class = &quot;character&quot;) + 2
#> [1] &quot;a2
2 + structure(&quot;a&quot;, class = &quot;character&quot;)
#> [1] &quot;2a&quot;
</pre>
<p>What if we try to dispatch on some new class?</p>
<pre>
`+.foo` &lt;- function(e1, e2) {
  paste0(e1, e2)
}
structure(&quot;a&quot;, class = &quot;foo&quot;) + 2
#> [1] &quot;a2
</pre>
<p>but no dice for just a regular atomic character object. Time to revisit the help pages.</p>
<p>In R, addition is limited to particular classes of objects, defined by the Ops group (there are also Math, Summary, and Complex groups). The methods for the Ops group members describe which classes can be involved in operations involving any of the Ops group members:<br>
<code><br>
&quot;+&quot;, &quot;-&quot;, &quot;*&quot;, &quot;/&quot;, &quot;^&quot;, &quot;%%&quot;, &quot;%/%&quot;<br>
&quot;&amp;&quot;, &quot;|&quot;, &quot;!&quot;<br>
&quot;==&quot;, &quot;!=&quot;, &quot;&lt;&quot;, &quot;&lt;=&quot;, &quot;>=&quot;, &quot;>&quot;<br>
</code> </p>
<p>These methods are:</p>
<pre>
methods(&quot;Ops&quot;)
 [1] Ops,array,array-method              
 [2] Ops,array,structure-method          
 [3] Ops,nonStructure,nonStructure-method
 [4] Ops,nonStructure,vector-method      
 [5] Ops,structure,array-method          
 [6] Ops,structure,structure-method      
 [7] Ops,structure,vector-method         
 [8] Ops,vector,nonStructure-method      
 [9] Ops,vector,structure-method         
[10] Ops.data.frame                      
[11] Ops.data.table*                     
[12] Ops.Date                            
[13] Ops.difftime                        
[14] Ops.factor                          
[15] Ops.numeric_version                 
[16] Ops.ordered                         
[17] Ops.POSIXt                          
[18] Ops.raster*                         
[19] Ops.roman*                          
[20] Ops.ts*                             
[21] Ops.unit*             
</pre>
<p>What’s missing from this list, in order for us to be able to just use “string” + “string” is a character method. What’s perhaps even more surprising is that there <i>is</i> a <code>roman</code> method! Whaaaat?</p>
<pre>
as.roman(&quot;1&quot;) + as.roman(&quot;5&quot;)
#> [1] VI
as.roman(&quot;2000&quot;) + as.roman(&quot;18&quot;)
#> [1] MMXVIII
</pre>
<p><img src="https://i0.wp.com/jcarroll.com.au/wp-content/uploads/2018/10/groove_small.gif?w=500&ssl=1" data-recalc-dims="1"></p>
<p>Since the operations need to be defined for all the members of the Ops group, we would also need to define what to do with, say, <code>*</code> between strings. When one side is a string and the other is a number, a reasonable approach might be that which was taken in the original post (using a new infix <code>%s*%</code>)</p>
<pre>
&quot;a&quot; %s*% 3
#> [1] &quot;aaa&quot; 
</pre>
<p>There is, of course, a function to do this already</p>
<pre>
strrep(&quot;a&quot;, 3)
#> [1] &quot;aaa&quot; 
</pre>
<p>but I could see creating <code>&quot;a&quot; * 3</code> as a shortcut to this. I don’t know what one would expect <code>&quot;a&quot; * &quot;b&quot;</code> to produce.</p>
<p>The problem with where this is heading is that we aren’t allowed to create the method for an atomic class, as <a rel="nofollow" href="https://twitter.com/JorisMeys" target="_blank">Joris Meys</a> and <a rel="nofollow" href="https://twitter.com/BrodieGaslam" target="_blank">Brodie Gaslam</a> point out on Twitter</p>
<blockquote class="twitter-tweet" data-lang="en">
<p lang="en" dir="ltr">Yes, you're right. Below is what I remembered, which suggested that if it were not sealed, it could be defined, but that isn't true b/c `do_arith` only dispatches on objects (as you point out), although in theory it could dispatch on atomics, but probably doesn't for speed. <a rel="nofollow" href="https://t.co/UXk6Tdm3lW" target="_blank">pic.twitter.com/UXk6Tdm3lW</a></p>
<p>— BrodieG (@BrodieGaslam) <a rel="nofollow" href="https://twitter.com/BrodieGaslam/status/1047838113052155904?ref_src=twsrc%5Etfw" target="_blank">October 4, 2018</a></p>
</blockquote>
<p></p>
<pre>
setMethod(&quot;+&quot;, c(&quot;character&quot;, &quot;character&quot;), function(e1, e2) paste0(e1, e2))
#> Error in setMethod(&quot;+&quot;, c(&quot;character&quot;, &quot;character&quot;), function(e1, e2) paste0(e1,  : 
#>   the method for function ‘+’ and signature e1=&quot;character&quot;, e2=&quot;character&quot; is sealed and cannot be re-defined
</pre>
<p>so no luck there. Brodie also links to <a rel="nofollow" href="https://stackoverflow.com/questions/1319698/why-doesnt-operate-on-characters-in-r/1321491#1321491" target="_blank">a Stack Overflow discussion</a> on this very topic where it is pointed out by <a rel="nofollow" href="https://twitter.com/MMaechler" target="_blank">Martin Mächler</a> that this has been discussed on <a rel="nofollow" href="https://stat.ethz.ch/pipermail/r-devel/2006-August/038991.html" target="_blank">r-devel</a> — that makes for some interesting historical weigh-ins on why this isn’t a thing in R. Incidentally, the small-world effect comes into play regarding that Stack Overflow post as one of the three answers happens to be a former work colleague of mine.</p>
<p>So, in the end, it seems the best we can do is the rather long-winded overwrite of <code>+</code> which checks if the arguments really are characters. I don’t mind this, and would probably use it if it was in base R or a package. The biggest issue that people seem to have with this is that it ‘looks like’ addition, but it’s not commutative. If that word is new to you, it just means that <code>x + y</code> should give the same answer as <code>y + x</code>. For numbers, the regular + satisfies this:</p>
<pre>
2 + 3
#> [1] 5
3 + 2
#> [1] 5
</pre>
<p>but when we try to do this with strings… not so much</p>
<pre>
&quot;a&quot; + &quot;b&quot;
#> [1] &quot;ab&quot;
&quot;b&quot; + &quot;a&quot;
#> [1] &quot;ba&quot;
</pre>
<p>This doesn’t particularly bother me, because I’m okay with this not actually being ‘mathematical addition’. The fun turn this then took was the suggestion from <a rel="nofollow" href="https://twitter.com/JorisMeys" target="_blank">Joris Meys</a> that <a rel="nofollow" href="https://docs.julialang.org/en/stable/manual/mathematical-operations/#Operator-Precedence-and-Associativity-1" target="_blank">Julia’s non-associative operators</a> is a strength of the language. There, the way that <a rel="nofollow" href="https://docs.julialang.org/en/stable/manual/mathematical-operations/#footnote-2" target="_blank">you group values matters</a></p>
<blockquote>
<p>a + b + c is parsed as +(a, b, c) not +(+(a, b), c).</p>
</blockquote>
<p><img src="https://i1.wp.com/jcarroll.com.au/wp-content/uploads/2018/10/wack.gif?resize=250%2C188&ssl=1" data-recalc-dims="1"></p>
<p>I’ll eventually get around to learning more Julia, but this is already hurting my brain.</p>
<p>That distinction may be of interest, however, to <a rel="nofollow" href="https://twitter.com/MilesMcBain/" target="_blank">Miles McBain</a>, whose concern was more about repeated applications of <code>+</code> being a bottleneck</p>
<blockquote class="twitter-tweet" data-lang="en">
<p lang="en" dir="ltr">I hate + for string concatenation. &quot;a&quot; + &quot;b&quot; + &quot;c&quot; is paste(&quot;a&quot;, paste(&quot;b&quot;,&quot;c&quot;)). So you end up copying the data in &quot;b&quot; and &quot;c&quot; twice due to the data being immutable. That can really add up fast with more +'s if you are careless. Like I was in my first programming job.</p>
<p>— Miles McBain (@MilesMcBain) <a rel="nofollow" href="https://twitter.com/MilesMcBain/status/1047743465562431489?ref_src=twsrc%5Etfw" target="_blank">October 4, 2018</a></p>
</blockquote>
<p></p>
<p>In that case, parsing as <code>+(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</code> is exactly what would be desired.</p>
<p>So, what’s the conclusion of all of this? I’ve learned (and re-learned) a heap more about how the Ops group works, I’ve played a lot with dispatch, and I’ve thought deeply about edge-cases for adding strings. I’ve also been exposed to a bit more Julia. All in all, a worthwhile dive into something potentially silly, but a lot of fun. If you have some thoughts on the matter, leave a comment here or reply on Twitter — I’d love to hear about another angle to this story.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://jcarroll.com.au/2018/10/06/adding-strings-in-r/"> R – Irregularly Scheduled Programming</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/vNc6EAnPNpg" height="1"></a></div>