将给定矩阵转换为 R 中的一维数组
在本文中,让我们讨论如何在 R 中将矩阵转换为一维数组。
使用的功能
- R中的matrix()函数用于创建矩阵
Syntax: matrix(data,nrow,ncol,byrow,dimnames)
Parameter:
- data-is the input vector which becomes the data elements of the matrix
- nrow-is the numbers of rows to be created
- ncol-is the numbers of columns to be created
- byrow-is a logical clue,if it is true then input vector elements are arranged by row
- dimname-is tha names assinged to rows and columns
- vector()函数用于将对象转换为向量。
句法:
vector(object)
方法
- 创建矩阵
- 将创建的矩阵传递给向量函数
- 打印数组
示例 1:
R
rows=c("r1","r2")
cols=c("c1","c2","c3","c4")
M=matrix(c(2:9),nrow=2,byrow=TRUE,dimnames=list(rows,cols))
print("Original matrix:")
print(M)
output=as.vector(M)
print("1D array :")
print(output)
R
rows=c("r1","r2","r3","r4")
cols=c("c1","c2","c3","c4")
M=matrix(c(2:17),nrow=4,byrow=TRUE,dimnames=list(rows,cols))
print("Original matrix:")
print(M)
output=as.vector(M)
print("1D array :")
print(output)
输出
[1] "Original matrix:"
c1 c2 c3 c4
r1 2 3 4 5
r2 6 7 8 9
[1] "1D array :"
[1] 2 6 3 7 4 8 5 9
我们也可以只转换给定数量的行,因为只需将所需的数字作为值传递给 nrow。
例子:
电阻
rows=c("r1","r2","r3","r4")
cols=c("c1","c2","c3","c4")
M=matrix(c(2:17),nrow=4,byrow=TRUE,dimnames=list(rows,cols))
print("Original matrix:")
print(M)
output=as.vector(M)
print("1D array :")
print(output)
输出:
[1] "Original matrix:"
c1 c2 c3 c4
r1 2 3 4 5
r2 6 7 8 9
r3 10 11 12 13
r4 14 15 16 17
[1] "1D array :"
[1] 2 6 10 14 3 7 11 15 4 8 12 16 5 9 13 17