toString() Function in R with Example

The toString() function first covers its argument into a character vector and then concatenates the result’s elements if the length is greater than 1. In R, a string is a vector of characters, and all scalars are one-dimensional vectors.

In R, there is no built-in string data type. Instead, it is called character, and you can use the is.character() function to check.

Type conversions in R work as you would expect. For example, adding the character string to a numeric vector converts all the vector items to the character.

toString() in R

The toString() is an inbuilt R helper function that produces a single character string describing an R object. The toString() function converts an R object to a character string. It converts an object to a character type, and then if you have passed the second argument, it will concatenate with it.


toString(x, width = NULL, ...)


x: It is an R object.

width: It is a maximum field width. Values of NULL or 0 indicate no maximum. The minimum value accepted is 6, and smaller values are taken as 6.

Return Value

The toString() function returns a character vector of length 1 is returned.


Let’s define a double vector and then use the toString() function to convert it into a string. In the R sense, a character.

dt <- c(1, 2, 3)
ds <- toString(dt)


[1] "double"
[1] "character"

As you can see that the toString() function converts a double to a string.

Convert Matrix to String in R

To create a matrix in R, use the matrix() function. Let’s apply a toString() function to the matrix and convert the matrix into a string.

mt <- matrix(c(1:9), 3, 3)
ds <- toString(mt)


[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 is it for toString() in the R tutorial.

See also

agrep() function in R

chartr() function in R

substr() function in R

Leave a Comment