How to unlist when converting dataframe to matrix?

I want to coerce a numeric dataframe into matrix and want to retain the row/column names. I tried to unlist.

mat <- as.matrix(unlist(df))

Input:

> dput(df)
structure(list(TCGA.2K.A9WE.01A = c("3.33370417925201", "3.26191613710211", 
"2.98072012253114", "3.45442444300391", "3.23147506581216"), 
    TCGA.2Z.A9J1.01A = c("3.34925376425734", "3.32510595062856", 
    "3.05313491041203", "3.63034209087263", "3.24014574406411"
    ), TCGA.2Z.A9J3.01A = c("3.30349695880794", "3.33666480834738", 
    "3.08982082695446", "3.70172491168742", "3.27383206099273"
    ), TCGA.2Z.A9J5.01A = c("3.38096309720271", "3.38548662709543", 
    "3.00519898142942", "3.57422385519763", "3.43484025303272"
    ), TCGA.2Z.A9J6.01A = c("3.36824732623076", "3.31393112898833", 
    "3.28265423939019", "3.58687437256901", "3.33930301693651"
    )), row.names = c("AAAS", "AARSD1", "AASS", "ABHD11", "ABHD14A"
), class = "data.frame")

Data structure

> class(df)
[1] "data.frame"

> typeof(df)
[1] "list"

>Solution :

You can apply as.matrix() directly without unlist()’ing:

mat <- as.matrix(df)
mode(mat) <- "numeric"

If you rather unlist() it seems there will be more steps:

mat           <- matrix(as.numeric(unlist(df)), ncol = ncol(df))
dimnames(mat) <- list(row.names(df), names(df))

Leave a Reply