R paste() Function - String Concatenation

R 语言实例R Language Examples

R paste() function is used to concatenate multiple strings or vectors together.

paste0() is a separator-free version of paste(), equivalent to paste(sep = "").

The syntax format of paste() function is as follows:

paste(..., sep = " ", collapse = NULL)
paste0(..., collapse = NULL)

Parameter description:

  • ...The strings or vectors to be concatenated.

  • sepSeparator when concatenating, default is a space.

  • collapseFurther merge the concatenated vector into a single string, using collapse as the separator.

Example

# Basic concatenation (separated by space by default)
result1 <- paste("Hello", "EXAMPLE", "R")
print(result1)

# Specify separator
result2 <- paste("2026", "05", "11", sep = "-")
print(result2)

# paste0 without separator
result3 <- paste0("ID_", 1:5)
print(result3)

# Use collapse to merge a vector into a single string
words <- c("R", "is", "powerful")
sentence <- paste(words, collapse = " ")
print(sentence)

Executing the above code produces the following result:

[1] "Hello EXAMPLE R"
[1] "2026-05-11"
[1] "ID_1" "ID_2" "ID_3" "ID_4" "ID_5"
[1] "R is powerful"

paste() is often used to dynamically generate labels or file names:

Example

# Generate month labels
months <- paste("Month", 1:12, sep = "")
print(months[1:5])

# Generate file path
path <- paste0("data/", c("sales", "inventory", "customers"), ".csv")
print(path)

Executing the above code produces the following result:

[1] "月份1" "月份2" "月份3" "月份4" "月份5"
[1] "data/sales.csv"      "data/inventory.csv"
[3] "data/customers.csv"

R 语言实例R Language Examples

Other Extensions