How to Convert Vector to String in R

Here are two ways to convert a vector to a string in R:

  1. Using paste()
  2. Using toString()

Method 1: Using paste()

Visual representation of the paste() function

Syntax

paste(x, sep=" ", collapse=NULL)

Parameters

  1. x: It is a vector having values.
  2. sep: It is a character string to separate the terms. Not NA_character_.
  3. collapse: It is an optional character string to separate the results. Not NA_character_. Use the collapse argument to convert a vector to a string.

Example

rv <- c("Ahsoka", "Din", "Grogu")
mando <- paste(rv, collapse = " ")

print(mando)

Output

[1] "Ahsoka Din Grogu"

You can use the collapse” argument to specify the delimiter between each word in the vector.

vec <- c("Krunal", "Ankit", "Rushabh", "Dhaval")

# Convert vector to string
str <- paste(vec, collapse = "--")

str

Output

[1] "Krunal--Ankit--Rushabh--Dhaval"

Method 2: Using toString()

Visual representation of the toString() function

Syntax

toString(x, width = NULL)

Parameters

  1. x: It is an R object.
  2. width: It is for the maximum field width. Values of NULL or 0 indicate no maximum. The minimum value allowed is 6; smaller values are perceived as 6.

Example

vec <- c("Ahsoka", "Din", "Grogu")

str <- toString(vec)
print(str)

Output

[1] "Ahsoka, Din, Grogu"

Let’s check the data type.

rv <- c("Ahsoka", "Din", "Grogu")

mando <- toString(rv)

print(typeof(mando))

Output

[1] "character"

Conclusion

The paste() function offers more flexibility with the collapse argument for custom separators while toString() is a quick option for a standard comma-separated format.

Leave a Comment