将向量的元素转换为 R 语言中的字符串 – toString()函数
R 编程语言中的toString()函数用于字符串。
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
R 语言示例中的toString()函数
示例 1: R 语言中 toString()函数的基本示例
R
# R program to illustrate
# toString function
# Initializing a string vector
x <- c("GFG", "Geeks", "GeeksforGeekss")
# Calling the toString() function
toString(x)
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)
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)
输出 :
[1] "GFG, Geeks, GeeksforGeekss"
示例 2:在 R 语言中使用 toString()函数进行格式化
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)
输出:
[1] "GF...."
[1] "GFG, ...."
[1] "GFG, G...."
示例 3:在 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)
输出:
[,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"