The toString() function in R is used to concatenate elements of a vector into a single string, with elements separated by a comma.
The toString() function is similar to paste(x, collapse = “, “) but with formatting and width control. While paste() is more versatile for general string concatenation, toString() is specifically designed for creating a concise, comma-separated representation of a vector.
Syntax
toString(x, width = NULL)
Parameters
- x: It is an R object.
- width: It is a maximum string width.
Return Value
It returns a character vector of length 1.
Example 1: Usage of toString() function
vec <- c(1, 2, 3)
vec
typeof(vec)
char_vec <- toString(vec)
char_vec
typeof(char_vec)
Output
[1] 1 2 3
[1] "double"
[1] "1, 2, 3"
[1] "character"
Example 2: Converting a matrix to a string
mat <- matrix(c(1:9), 3, 3)
mat
typeof(mat)
char_vec <- toString(mat)
char_vec
typeof(char_vec)
Output
[1] "integer"
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[1] "character"
[1] "1, 2, 3, 4, 5, 6, 7, 8, 9"
That’s it!
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.