在 R 编程中将对象转换为矩阵 - as.matrix()函数
R 编程语言中的as.matrix()函数用于将对象转换为矩阵。
Syntax: as.matrix(x)
Parameters:
- x: Object to be converted
R 示例中的 as.matrix()函数
示例 1:使用 as.matrix() 将向量转换为矩阵
R
# R program to convert an object to matrix
# Creating a vector
x <- c(1:9)
# Calling as.matrix() Function
as.matrix(x)
R
# R program to convert an object to matrix
# Calling pre-defined data set
BOD
# Calling as.matrix() Function
as.matrix(BOD)
输出:
[, 1]
[1, ] 1
[2, ] 2
[3, ] 3
[4, ] 4
[5, ] 5
[6, ] 6
[7, ] 7
[8, ] 8
[9, ] 9
示例 2:使用 as.matrix() 将 Dataframe 转换为矩阵
R
# R program to convert an object to matrix
# Calling pre-defined data set
BOD
# Calling as.matrix() Function
as.matrix(BOD)
输出:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Time demand
[1, ] 1 8.3
[2, ] 2 10.3
[3, ] 3 19.0
[4, ] 4 16.0
[5, ] 5 15.6
[6, ] 7 19.8