What is the toString() Function in R

The toString() function in R is used to convert an object into a single character string.

Syntax

toString(x, width = NULL)

Parameters

  1. x: It is an R object.
  2. width: It is a maximum string width.

Return Value

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

Example 1: Converting a vector to a string using the toString()

Let’s define and convert a vector into a string using the toString() function. In the R sense, it is a character.

dt <- c(1, 2, 3)

typeof(dt)

ds <- toString(dt)

typeof(ds)

Output

[1] "double"

[1] "character"

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

Example 2: Converting a matrix to a string using the toString()

You can pass the matrix to the toString() function to convert the matrix to a string.

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

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.

Leave a Comment