toString() Function in detail
The toString() function in R is used to generate a single character string that describes an R object.
Syntax:
toString(x, width = NULL)
Parameters:
- x: An R object (e.g., vector, matrix, etc.)
- width: Suggestion for the maximum field width. Values of
NULLor0imply no maximum. The minimum accepted value is 6, and smaller values are treated as 6.
toString() Function in R Language Examples
Example 1: Basic Example of toString() Function
# R program to illustrate
# toString function
# Initializing a numeric vector
vec <- c(1, 2, 3, 4, 5)
# Calling the toString() function
result <- toString(vec)
print(result)
Output:
[1] "1, 2, 3, 4, 5"
Example 2: Formatting with toString() Function
# R program to illustrate
# toString function with width parameter
# Initializing a character vector
chars <- c("Apple", "Banana", "Cherry")
# Applying the toString() function with different widths
print(toString(chars, width = 6))
print(toString(chars, width = 10))
print(toString(chars, width = 15))
Output:
[1] "App..."
[1] "Apple, ..."
[1] "Apple, Ba..."
Example 3: Convert Matrix to String
# Matrix with 2 rows and 3 columns
mat <- matrix(c(10, 20, 30, 40, 50, 60), nrow = 2, ncol = 3)
# Printing the matrix
print("Matrix:")
print(mat)
# Converting matrix to string
mat_str <- toString(mat)
# Printing the string representation
print("Matrix as String:")
print(mat_str)
Output:
[1] "Matrix:"
[,1] [,2] [,3]
[1,] 10 30 50
[2,] 20 40 60
[1] "Matrix as String:"
[1] "10, 20, 30, 40, 50, 60"