Last active
October 4, 2018 07:52
-
-
Save jonocarroll/81d5f9a4b4faa265cf2946781d9d9ea7 to your computer and use it in GitHub Desktop.
Python/Javascript String Concatenation in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
`+` <- 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because this is a binary function acting left-to-right, the
paste
will only start as soon as a character is encountered, sobut