Create dataframe from a matrix

前端 未结 5 1442
孤城傲影
孤城傲影 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条回答
  •  孤街浪徒
    2020-12-07 19:27

    Using dplyr and tidyr:

    library(dplyr)
    library(tidyr)
    
    df <- as_data_frame(mat) %>%      # convert the matrix to a data frame
      gather(name, val, C_0:C_1) %>%  # convert the data frame from wide to long
      select(name, time, val)         # reorder the columns
    
    df
    # A tibble: 6 x 3
       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
    

提交回复
热议问题