英文:
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"
(Note: The provided text appears to be code and data. If you have any specific translation needs or questions, please let me know.)
英文:
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"
答案1
得分: 2
你可以直接使用as.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))
英文:
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))
答案2
得分: 0
你可以将每一列转换为数字,然后将其放入一个矩阵中,如下所示:
as.matrix(sapply(df, as.numeric))
# 添加行名
row.names(mat) <- row.names(df)
英文:
You can covert each column to a numeric then put it into a matrix like so:
as.matrix(sapply(df,as.numeric))
#add row names
row.names(mat) <- row.names(df)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论