如何取消列表时转换 Dataframe 矩阵?

fkvaft9z  于 2023-05-26  发布在  其他
关注(0)|答案(2)|浏览(146)

我想强制一个数字数据框到矩阵,并希望保留行/列名。我试着取消登记。

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

输入:

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

数据结构

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

> typeof(df)
[1] "list"
68de4m5k

68de4m5k1#

您可以直接以.matrix()的形式应用,而无需unlist():

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

如果你选择unlist(),似乎会有更多的步骤:

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

ef1yzkbh2#

你可以把每一列转换成一个数字,然后把它放入一个矩阵中,如下所示:

as.matrix(sapply(df,as.numeric))
#add row names
row.names(mat) <- row.names(df)

相关问题