R语言 将矩阵转换为矢量
在这篇文章中,我们将用R编程语言把给定的矩阵转换成矢量。
按行将矩阵 转换 为 矢量
方法1:使用c()函数
只需传递矩阵的名称就可以完成这项工作。
语法:
c(matrix_name)
其中 matrix_name 是输入矩阵的名称
例1 :
# create a matrix with 12 elements
# with 4 rows and 3 columns
matrix=matrix(1:12,nrow=4,ncol=3)
print(matrix)
# convert matrix to vector using c()
# function
a=c(matrix)
print(a)
输出:
例2 :
# create a matrix with 16 elements
# with 4 rows and 4 columns
matrix=matrix(1:16,nrow=4,ncol=4)
print(matrix)
# convert matrix to vector using
# c() function
a=c(matrix)
print(a)
输出:
方法2:使用as.vector()函数
这个函数用于将矩阵转换为矢量,因此再次简单地传递矩阵名称就可以了。
语法:
as.vector(matrix)
例子
# create a matrix with 12 elements
# with 4 rows and 3 columns
matrix=matrix(1:12,nrow=4,ncol=3)
print(matrix)
# convert matrix to vector using
# as.vector() function
a=as.vector(matrix)
print(a)
输出:
例2 :
# create a matrix with 16 elements with 4 rows and 4 columns
matrix=matrix(1:16,nrow=4,ncol=4)
print(matrix)
# convert matrix to vector using as.vector() function
a=as.vector(matrix)
print(a)
输出
矩阵按列 转换 为矢量
方法1:将c()函数与t()函数一起使用
t()函数用于对给定的矩阵进行转置。它将把行转为列,把列转为行。
语法:
t(matrix)
其中,matrix是输入矩阵
应用t()后,我们可以应用c()和as.vector()函数来将矩阵转换为向量。
语法 :
c(t(matrix))
例1 :
# create a matrix with 12 elements
# with 4 rows and 3 columns
matrix=matrix(1:12,nrow=4,ncol=3)
print(matrix)
# convert matrix to vector using
# c() function along with t()
a=c(t(matrix))
print(a)
输出:
例2 :
# create a matrix with 12 elements
# with 2 rows and 6 columns
matrix=matrix(1:12,nrow=2,ncol=6)
print(matrix)
# convert matrix to vector using
# c() function along with t()
a=c(t(matrix))
print(a)
输出:
方法2:将as.vector()函数与t()函数一起使用
t()的工作与上述相同。取完转置后,使用as.vector()将矩阵转换为矢量。
语法:
as.vector(t(matrix))
例子
# create a matrix with 12 elements
# with 2 rows and 6 columns
matrix=matrix(1:12,nrow=2,ncol=6)
print(matrix)
# convert matrix to vector using
# as.vector() function along with t()
a=as.vector(t(matrix))
print(a)
输出:
例2 :
# create a matrix with 4 elements
# with 2 rows and 2 columns
matrix=matrix(1:4,nrow=2,ncol=2)
print(matrix)
# convert matrix to vector using
# as.vector() function along with t()
a=as.vector(t(matrix))
print(a)
输出