Open In App

Convert elements of a Vector to Strings in R Language – toString() Function

Improve
Improve
Like Article
Like
Save
Share
Report

toString() function in R Programming Language is used to produce a single character string describing an R object.

Syntax: toString(x, width = NULL)

Parameters: 

  • x: R object
  • width: Suggestion for the maximum field width. Values of NULL or 0 indicate no maximum. The minimum value accepted is 6 and smaller values are taken as 6 
     

toString() function in R Language Example

Example 1: Basic example of toString() Function in R Language

R




# R program to illustrate
# toString function
 
# Initializing a string vector
x <- c("GFG", "Geeks", "GeeksforGeekss")
 
# Calling the toString() function
toString(x)


Output : 

[1] "GFG, Geeks, GeeksforGeekss"

Example 2:  Formatting with toString() Function in R Language

R




# R program to illustrate
# toString function
 
# Initializing a string vector
x <- c("GFG", "Geeks", "GeeksforGeekss")
 
# Calling the toString() function
toString(x, width = 2)
toString(x, width = 8)
toString(x, width = 10)


Output: 

[1] "GF...."
[1] "GFG, ...."
[1] "GFG, G...."

Example 3: Convert Matrix to String in R

R




# Matrix having 3 rows and 3 columns
# filled by a single constant 5
mat <- (matrix(5, 3, 3))
print(mat)
str <- toString(mat)
print("String")
print(str)


Output:

     [,1] [,2] [,3]
[1,]    5    5    5
[2,]    5    5    5
[3,]    5    5    5
[1] "String"
[1] "5, 5, 5, 5, 5, 5, 5, 5, 5"


Last Updated : 25 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads