Go to TogaWare.com Home Page. Data Science Desktop Survival Guide
by Graham Williams
Duck Duck Go


Concatenate Strings

20180720 One of the most basic operations in string manipulation is the concatenate operation. R provides alternatives for doing so but a modern favourite is the stringi::https://www.rdocumentation.org/packages/stringi/topics/operator.
"abc" %s+% "def" %s+% "ghi"
## [1] "abcdefghi"
c("abc", "def", "ghi", "jkl") %s+% c("mno")
## [1] "abcmno" "defmno" "ghimno" "jklmno"
c("abc", "def", "ghi", "jkl") %s+% c("mno", "pqr")
## [1] "abcmno" "defpqr" "ghimno" "jklpqr"
c("abc", "def", "ghi", "jkl") %s+% c("mno", "pqr", "stu", "vwx")
## [1] "abcmno" "defpqr" "ghistu" "jklvwx"

The tidy function for concatenating strings is stringr::str_c(). A sep= can be used to specify a separator for the concatenated strings.

str_c("hello", "world")
## [1] "helloworld"
str_c("hello", "world", sep=" ")
## [1] "hello world"

We can also concatenate strings using glue::glue().

glue("hello", "world")
## helloworld

The traditional base::cat() function returns the concatenation of the supplied strings. Numeric and other complex objects are converted into character strings.

cat("hello", "world")
## hello world
cat ("hello", 123, "world")
## hello 123 world

Yet another alternative (and there are many) is the function base::paste(). Notice that it separates the concatenated strings with a space.

paste("hello", "world")
## [1] "hello world"

Support further development by purchasing the PDF version of the book.
Other online resources include the GNU/Linux Desktop Survival Guide.
Books available on Amazon include Data Mining with Rattle and Essentials of Data Science.
Popular open source software includes rattle and wajig.
Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 2000-2020 Togaware Pty Ltd. . Creative Commons ShareAlike V4.