R toString() Function

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

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

Return Value

It returns a character vector of length 1.

Example 1: Usage of toString() function

Converting a vector to a string using the toString()

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

Converting a matrix to a string using the toString()

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!

Leave a Comment