是否有一个现成的功能将矩阵转换成行,列和值的数据框? [英] Is there a ready made function to transform a matrix into data frame of rows, columns and values?
问题描述
我想重写一个矩阵作为一个数据框,一列为行,一列用于列,另一列用于存储在矩阵中的实际值。
让我们有一个这样的示例矩阵:
Let us have an example matrix like that:
mat <- matrix(paste0(rep(1:5,3), rep(1:3,each=5)), 5, 3)
mat
# [,1] [,2] [,3]
# [1,] "11" "12" "13"
# [2,] "21" "22" "23"
# [3,] "31" "32" "33"
# [4,] "41" "42" "43"
# [5,] "51" "52" "53"
使用 as.vector()
和 rep()
我可以构造想要的结果:
With as.vector()
and rep()
I can construct the wanted result as such:
values <- as.vector(mat)
rows <- rep(seq_len(dim(mat)[1]), dim(mat)[2])
columns <- rep(seq_len(dim(mat)[2]), each=dim(mat)[1])
df <- data.frame(rows, columns, values)
df
# rows columns values
# 1 1 1 11
# 2 2 1 21
# 3 3 1 31
# 4 4 1 41
# 5 5 1 51
# 6 1 2 12
# 7 2 2 22
# 8 3 2 32
# 9 4 2 42
# 10 5 2 52
# 11 1 3 13
# 12 2 3 23
# 13 3 3 33
# 14 4 3 43
# 15 5 3 53
现在,是否有一个准备就绪的可能更多的性能功能在R或其中一个软件包中执行此操作?
Now, is there a ready made maybe more performant function in R or one of its package to do this?
推荐答案
使用 reshape2
package:
With the reshape2
package:
melt(mat)
Var1 Var2 value
1 1 1 11
2 2 1 21
3 3 1 31
4 4 1 41
5 5 1 51
6 1 2 12
7 2 2 22
8 3 2 32
9 4 2 42
10 5 2 52
11 1 3 13
12 2 3 23
13 3 3 33
14 4 3 43
15 5 3 53
基础R的解决方案:
as.data.frame.table(mat)
,上面的代码不会产生所需的输出,因为矩阵没有行/列名称,而as.data.frame.table()会放置字母。但是,如果矩阵具有行/列名称,那么它的作用如下:
however, the above code does not produce the desired output because the matrix has no row/col names, and as.data.frame.table() puts letters instead. However, if the matrix has row/col names this works:
rownames(mat) = 1:5
colnames(mat) = 1:3
as.data.frame.table(mat)
就是说,$ code> fusion 在我的经验中使用大型矩阵的速度更快。
That being said, melt
is way faster with large matrices in my experience.
这篇关于是否有一个现成的功能将矩阵转换成行,列和值的数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!