将字符矩阵转换为 R 中的数字矩阵
在本文中,我们将了解如何在 R 编程语言中将给定的字符矩阵转换为数字。将字符矩阵转换为数字矩阵,我们将使用 as.numeric() 和 matrix() 函数。
使用的功能
- as.numeric()函数:该函数用于将给定的列转换为 r 语言中的数值列。
Syntax: as.numeric(x, …)
Parameter:
x: object to be coerced.
Returns: The numeric type object in r language.
- matrix()函数: r 语言中的该函数用于创建矩阵。
Syntax: matrix(data, nrow, ncol, byrow, dimnames)
Parameter:
- data: is the input vector that becomes the data elements of the matrix.
- nrow: is the number of rows to be created.
- ncol: is the number of columns to be created.
- byrow: is a logical clue. If TRUE then the input vector elements are arranged by row.
- dimname: is the names assigned to the rows and columns.
Returns: It will return the matrix of the provided data to the user.
这是将给定字符矩阵转换为数字矩阵的最简单方法之一,因为在这种方法下,用户只需要使用给定字符矩阵的名称作为参数调用as.numeric()函数,这将帮助用户将字符矩阵转换为数字向量,在下一步中,用户必须使用数字向量(由 as.numeric函数创建)调用另一个函数matrix()作为回报,该函数将返回给用户的数字矩阵。这样,用户就结束了从 r 语言的 matrix()函数接收数字矩阵的过程。
示例 1:
在这个例子中,我们将使用 as.numeric函数将给定的 3 列 3 行 9 个元素的字符矩阵转换为数字矩阵,matrix()函数是 r 语言。
R
# Creating character matrix
gfg_character_matrix <- matrix(c("1","2","3","4",
"5","6","7","8","9"),
ncol = 3)
print("Print character matrix")
print(gfg_character_matrix)
# Convert to numeric matrix
gfg_numeric_matrix <- matrix(
as.numeric(gfg_character_matrix), ncol = 3)
print("Print numeric matrix")
print(gfg_numeric_matrix )
R
# Creating character matrix
gfg_character_matrix <- matrix(c("-4","2","8","7","-10",
"-40","78","-54","74",
"87","0","1","41","24",
"91","11"),
ncol = 4)
print("Character matrix")
print(gfg_character_matrix)
# Convert to numeric matrix
gfg_numeric_matrix <- matrix(
as.numeric(gfg_character_matrix), ncol = 4)
print("Numeric matrix")
print(gfg_numeric_matrix )
输出:
[1] "Print character matrix"
[,1] [,2] [,3]
[1,] "1" "4" "7"
[2,] "2" "5" "8"
[3,] "3" "6" "9"
[1] "Print numeric matrix"
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
示例 2:
在这个例子中,我们将使用 as.numeric函数将给定的 4 列 4 行 16 个元素的字符矩阵转换为数字矩阵,matrix()函数是 r 语言。
电阻
# Creating character matrix
gfg_character_matrix <- matrix(c("-4","2","8","7","-10",
"-40","78","-54","74",
"87","0","1","41","24",
"91","11"),
ncol = 4)
print("Character matrix")
print(gfg_character_matrix)
# Convert to numeric matrix
gfg_numeric_matrix <- matrix(
as.numeric(gfg_character_matrix), ncol = 4)
print("Numeric matrix")
print(gfg_numeric_matrix )
输出:
[1] "Character matrix"
[,1] [,2] [,3] [,4]
[1,] "-4" "-10" "74" "41"
[2,] "2" "-40" "87" "24"
[3,] "8" "78" "0" "91"
[4,] "7" "-54" "1" "11"
[1] "Numeric matrix"
[,1] [,2] [,3] [,4]
[1,] -4 -10 74 41
[2,] 2 -40 87 24
[3,] 8 78 0 91
[4,] 7 -54 1 11