Here are two ways to convert a vector to a string in R:
- Using paste()
- Using toString()
Method 1: Using paste()
Syntax
paste(x, sep=" ", collapse=NULL)
Parameters
- x: It is a vector having values.
- sep: It is a character string to separate the terms. Not NA_character_.
- 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()
Syntax
toString(x, width = NULL)
Parameters
- x: It is an R object.
- 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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.