从矩阵创建数据框 [英] Create dataframe from a matrix

查看:82
本文介绍了从矩阵创建数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取与现有矩阵具有相同数据的数据框?

How to get a data frame with the same data as an already existing matrix has?

我的矩阵的简化示例:

mat <- matrix(c(0, 0.5, 1, 0.1, 0.2, 0.3, 0.3, 0.4, 0.5),
              ncol = 3, nrow = 3,
              dimnames = list(NULL, c("time", "C_0", "C_1")))

> mat
     time C_0 C_1
[1,]  0.0 0.1 0.3
[2,]  0.5 0.2 0.4
[3,]  1.0 0.3 0.5

我想创建一个看起来像这样的数据框:

I would like to create a data frame that looks like this:

     name   time   val
1    C_0    0.0    0.1
2    C_0    0.5    0.2
3    C_0    1.0    0.3
4    C_1    0.0    0.3
5    C_1    0.5    0.4
6    C_1    1.0    0.5

我的所有尝试都很笨拙,例如:

All my attempts are quite clumsy, for example:

data.frame(cbind(c(rep("C_1", 3), rep("C_2", 3)),
                 rbind(cbind(mat[,"time"], mat[,"C_0"]),
                       cbind(mat[,"time"], mat[,"C_1"]))))

有人知道如何更优雅地做到这一点吗?请注意,我的真实数据还有更多列(40列).

Does anyone have an idea of how to do this more elegantly? Please note that my real data has a few more columns (40 columns).

推荐答案

如果将time列更改为行名,则可以将as.data.frame(as.table(mat))用于此类简单情况.

If you change your time column into row names, then you can use as.data.frame(as.table(mat)) for simple cases like this.

示例:

data <- c(0.1, 0.2, 0.3, 0.3, 0.4, 0.5)
dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
as.data.frame(as.table(mat))
  time name Freq
1    0  C_0  0.1
2  0.5  C_0  0.2
3    1  C_0  0.3
4    0  C_1  0.3
5  0.5  C_1  0.4
6    1  C_1  0.5

在这种情况下,时间和名称都是两个因素.您可能想将时间转换回数字,或者没关系.

In this case time and name are both factors. You may want to convert time back to numeric, or it may not matter.

这篇关于从矩阵创建数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆