Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Last active October 4, 2018 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonocarroll/81d5f9a4b4faa265cf2946781d9d9ea7 to your computer and use it in GitHub Desktop.
Save jonocarroll/81d5f9a4b4faa265cf2946781d9d9ea7 to your computer and use it in GitHub Desktop.
Python/Javascript String Concatenation in R
`+` <- function(e1, e2) {
## unary
if (missing(e2)) return(e1)
if (!is.na(suppressWarnings(as.numeric(e1))) & !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) & is.na(suppressWarnings(as.numeric(e1)))) |
(is.character(e2) & is.na(suppressWarnings(as.numeric(e2))))) {
## at least one true character
return(paste0(e1, e2))
} else {
## both numeric
return(base::`+`(e1, e2))
}
}
"a" + "b"
#> [1] "ab"
"a" + 2
#> [1] "a2"
2 + 2
#> [1] 4
2 + "a"
#> [1] "2a"
"2" + "2"
#> [1] 4
"butter" + "fly"
#> [1] "butterfly"
"susan" + "album" + "party"
#> [1] "susanalbumparty"
2 + "edgy" + 4 + "me"
#> [1] "2edgy4me"
+ 1
#> [1] 1
+ "a"
#> [1] "a"
@jonocarroll
Copy link
Author

Because this is a binary function acting left-to-right, the paste will only start as soon as a character is encountered, so

"tit" + 2 + 2 + "tat"
#> [1] "tit22tat"

but

2 + 2 + "crazy"
#> [1] "4crazy"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment