Strings can be combined using paste, paste0, and other utilities. When using paste, the default separator is space:
paste("I","think","therefore","I","am")
We can use a different separator by using the sep flag:
paste("I","think","therefore","I","am", sep="-")
paste0 is an extension of paste where the separator is null. As a result, all strings are concatenated into a single string unless separators are specified:
paste0("I","think","therefore","I","am")
In addition to the sep flag, there is also a collapse flag that can be used to separate the results:
paste("grade",c("A","B","C"), sep=" ") # paste with separator space paste("grade",c("A","B","C"), sep=" ", collapse=",") # paste with separator space and collapse with "," (comma) paste0("grade",c("A","B","C"), collapse=",") # paste0 is set to the separator "" (null)
The stringr package in R also contains several useful string manipulation functions. One of them, called str_c has been shown as follows:
library(stringr) str_c("grade",c("A","B","C",NULL)) # str_c from the stringr package is a newer (and somewhat simpler) alternative to paste/paste0 in R
We can split the string using the following line of code:
strsplit("I think, therefore I am",",")
Compared to strsplit, the tstrsplit function performs a transpose operation on the split vector. This is helpful when splitting strings and updating say, a column in a DataFrame:
tstrsplit("I think, therefore I am",",")
The difference can be easily observed herein:
# Create a simple data frame df <- data.frame(a=c(1,2)) # strsplit creates a vector df$s <- strsplit("I think, therefore I am",",") df # a s # 1 1 I think, therefore I am # 2 2 I think, therefore I am # tstrsplit creates a transpose of the vector, t df$s <- tstrsplit("I think, therefore I am",",") df # a s # 1 1 I think # 2 2 therefore I am