R语言 如何把矩阵转换为向量列表
在这篇文章中,我们将学习如何在R编程语言中把矩阵转换成向量列表。
将矩阵转换为按列排列的向量列表
方法1:使用 as.list() 函数
要将矩阵的列转换为向量列表,我们首先需要将矩阵转换为数据框架对象,这可以通过使用 as.data.frame(matrix_name) 来完成 , 它以我们的矩阵为参数并返回一个数据框架 。 一旦我们的矩阵被转换为数据框架,我们可以将我们新创建的(通过转换)数据框架作为参数传给 as.list(dataframe_name) 函数,它将我们的数据框架转换为一个向量列表。
语法:
as.list(as.data.frame(matrix_name))
例1 :
mat<-matrix(1:20, ncol=4)
print("Sample Matrix")
mat
print("List of Vectors after conversion")
list<-as.list(as.data.frame(mat))
list
输出 。
[1] "Sample Matrix"
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
[1] "List of Vectors after conversion"
V1
[1] 1 2 3 4 5V2
[1] 6 7 8 9 10
V3
[1] 11 12 13 14 15V4
[1] 16 17 18 19 20
方法2:使用 split() 和 rep( )。
我们将我们的样本矩阵和复制的向量元素作为参数传给split()函数,它返回我们的列表对象。
split()函数用于将数据向量划分为由提供的因子定义的组。
语法: split(x, f)
参数:
- x : 代表数据向量或数据框
- f :代表划分数据的因素
rep() 用于在R编程中复制向量的元素。
语法: Rep(x, times)
参数。
- x :代表数据向量或数据框
- times: 出现的频率
返回 :返回复制的向量。
例子 。
mat<-matrix(1:20, ncol=4)
print("Sample Matrix")
mat
list = split(mat, rep(1:ncol(mat), each = nrow(mat)))
print("After converting Matrix into a List")
print(list)
输出 。
[1] "Sample Matrix"
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
[1] "After converting Matrix into a List"
`1`
[1] 1 2 3 4 5`2`
[1] 6 7 8 9 10
`3`
[1] 11 12 13 14 15`4`
[1] 16 17 18 19 20
通过行将矩阵转换为向量列表
方法1:使用as.list()
使用此方法的方法与上面一样,但要得到行,我们首先要得到矩阵的转置。可以使用 t ( matrix_name) 函数。
语法 。
as.list(as.data.frame(t(matrix_name)))
例子 。
mat<-matrix(1:20, ncol=4)
print("Sample Matrix")
mat
print("List of Vectors after conversion")
list<-as.list(as.data.frame(t(mat)))
list
输出 。
[1] "Sample Matrix"
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
[1] "List of Vectors after conversion"
V1
[1] 1 6 11 16V2
[1] 2 7 12 17
V3
[1] 3 8 13 18V4
[1] 4 9 14 19
$V5
[1] 5 10 15 20
方法2:使用split()和rep() 。
同样,在这个方法中,我们也必须找到矩阵的转置,其余的方法与上面一样。
语法:
split(mat, rep(1:ncol(mat), each = nrow(mat)))
例子 。
mat<-matrix(1:20, ncol=4)
print("Sample Matrix")
mat
t_mat=t(mat)
list = split(
t_mat, rep(1:ncol(t_mat), each = nrow(t_mat)))
print("After converting Matrix into a List")
print(list)
输出 。
[1] "Sample Matrix"
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
[1] "After converting Matrix into a List"
`1`
[1] 1 6 11 16`2`
[1] 2 7 12 17
`3`
[1] 3 8 13 18`4`
[1] 4 9 14 19
$`5`
[1] 5 10 15 20