从R中的矩阵创建数据帧 [英] Create data frame from a matrix in R

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

问题描述

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

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).

推荐答案

如果您更改了时间列成行名,那么您可以使用 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.

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

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