R Joining Strings
Joining puts strings together into one longer string. paste and paste0 both join strings in R.
Joining with a space
paste joins words with a space between them. The second print joins three words into one string.
print(paste("Hello", "World"))
print(paste("red", "green", "blue"))A chosen separator
paste uses the sep value as the separator. Both prints join the parts with a dash.
print(paste("2026", "10", "25", sep = "-"))
print(paste("Mon", "Tue", sep = "-"))Joining with nothing
paste0 joins each pair with nothing between the parts. The results read as single strings.
print(paste0("Hello", "World"))
print(paste0("file", "1"))Example
first <- "Ada"
last <- "Lovelace"
print(paste(first, last))
print(paste(first, last, sep = "-"))
print(paste0(first, last))Key points
- paste joins strings with a space by default.
- The sep argument in paste sets the separator between the strings.
- paste0 joins strings with nothing between them.
- paste adds its separator between every pair of strings.
- A paste call returns one string.
In this example, paste joins the first and last names with a space. The sep argument swaps the space for a dash. paste0 then joins the names with nothing between them.
Note
paste can also fold a whole vector into one string with collapse, and the vectors lessons use that form later.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(paste0("file", "1")) show?