Create dataframe from a matrix

前端 未结 5 1431
孤城傲影
孤城傲影 2020-12-07 18:54

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         


        
5条回答
  •  萌比男神i
    2020-12-07 19:23

    You can use stack from the base package. But, you need first to coerce your matrix to a data.frame and to reorder the columns once the data is stacked.

    mat <- as.data.frame(mat)
    res <- data.frame(time= mat$time,stack(mat,select=-time))
    res[,c(3,1,2)]
    
      ind time values
    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
    

    Note that stack is generally more efficient than the reshape2 package.

提交回复
热议问题