Create dataframe from a matrix

user1981275 picture user1981275 · Apr 8, 2013 · Viewed 131.5k times · Source

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

A simplified example of my matrix:

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"]))))

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

Answer

Greg Snow picture Greg Snow · Apr 8, 2013

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

Example:

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.