How to Use paste and paste0 in R: Simple String Concatenation
In R,
paste() joins strings with a space or a specified separator, while paste0() concatenates strings directly without any separator. Use paste() when you want spaces or custom separators, and paste0() for quick, tight joining of strings.Syntax
paste() syntax: combines strings with a separator (default is a space).
paste(..., sep = " ", collapse = NULL)
...: strings or vectors to joinsep: separator between elements (default is space)collapse: optional string to join all results into one
paste0() syntax: same as paste() but sep is always empty (no separator).
paste0(..., collapse = NULL)
r
paste(..., sep = " ", collapse = NULL)
paste0(..., collapse = NULL)Example
This example shows how paste() adds spaces by default or custom separators, while paste0() joins strings without spaces.
r
a <- "Hello" b <- "World" # Using paste with default separator (space) result1 <- paste(a, b) # Using paste with custom separator result2 <- paste(a, b, sep = ", ") # Using paste0 (no separator) result3 <- paste0(a, b) result1 result2 result3
Output
[1] "Hello World"
[1] "Hello, World"
[1] "HelloWorld"
Common Pitfalls
One common mistake is expecting paste0() to add spaces automatically; it does not add any separator. Another is forgetting to set sep in paste() when you want a different separator than space. Also, mixing vectors without collapse can produce unexpected results.
r
x <- c("a", "b") y <- c("1", "2") # Wrong: expecting spaces with paste0 wrong <- paste0(x, y) # Right: use paste with sep right <- paste(x, y, sep = "-") # Using collapse to join all into one string collapsed <- paste(x, y, sep = "-", collapse = ",") wrong right collapsed
Output
[1] "a1" "b2"
[1] "a-1" "b-2"
[1] "a-1,b-2"
Quick Reference
| Function | Separator Used | Use Case |
|---|---|---|
| paste() | Space by default or custom with sep | Join strings with spaces or custom separators |
| paste0() | No separator | Join strings tightly without spaces |
| sep parameter | Custom separator in paste() | Change separator between strings |
| collapse parameter | Join vector elements into one string | Combine multiple results into one string |
Key Takeaways
Use paste() to join strings with spaces or custom separators.
Use paste0() to join strings without any separator.
Remember paste0() does not add spaces automatically.
Use sep parameter in paste() to change the separator.
Use collapse to combine vector results into a single string.