0
0
R-programmingHow-ToBeginner · 3 min read

How to Concatenate Strings in R: Simple Syntax and Examples

In R, you concatenate strings using the paste() or paste0() functions. paste() joins strings with a space by default, while paste0() joins them without any separator.
📐

Syntax

The main functions to concatenate strings in R are paste() and paste0().

  • paste(..., sep = " "): Joins strings with a separator, default is a space.
  • paste0(...): Joins strings without any separator (equivalent to paste(..., sep = "")).
r
paste(string1, string2, sep = "separator")
paste0(string1, string2)
💻

Example

This example shows how to join two strings with a space using paste() and without space using paste0().

r
str1 <- "Hello"
str2 <- "World"

# Using paste() with default separator (space)
result1 <- paste(str1, str2)

# Using paste() with custom separator
result2 <- paste(str1, str2, sep = ", ")

# Using paste0() with no separator
result3 <- paste0(str1, str2)

result1
result2
result3
Output
[1] "Hello World" [1] "Hello, World" [1] "HelloWorld"
⚠️

Common Pitfalls

One common mistake is expecting paste() or paste0() to modify the original strings. They return a new string instead. Also, forgetting the sep argument in paste() can lead to unexpected spaces.

Another pitfall is using the + operator to join strings, which does not work in R.

r
# Wrong way: Using + operator (will cause error)
# "Hello" + "World"

# Right way:
paste("Hello", "World")
paste0("Hello", "World")
📊

Quick Reference

FunctionDescriptionDefault Separator
paste(..., sep = " ")Concatenate strings with a separatorSpace (" ")
paste0(...)Concatenate strings without any separatorNone (empty string)

Key Takeaways

Use paste() to join strings with a space or custom separator.
Use paste0() to join strings without any separator.
Do not use + operator for string concatenation in R.
paste() and paste0() return new strings; they do not change original variables.
Specify the sep argument in paste() to control the separator.