Converting from a list to numeric in R

风流意气都作罢 提交于 2019-12-02 16:50:20

Here is a shorter/faster way to turn your data.frame into a numeric matrix:

data <- data.matrix(data)

There is also

data <- as.matrix(data)

but one important difference is if your data contains a factor or character column: as.matrix will coerce everything into a character matrix while data.matrix will always return a numeric or integer matrix.

data <- data.frame(
  logical   = as.logical(c(TRUE, FALSE)),
  integer   = as.integer(c(TRUE, FALSE)),
  numeric   = as.numeric(c(TRUE, FALSE)),
  factor    = as.character(c(TRUE, FALSE))
)

data.matrix(data)
#      logical integer numeric factor
# [1,]       1       1       1      2
# [2,]       0       0       0      1

as.matrix(data)
#      logical integer numeric factor 
# [1,] " TRUE" "1"     "1"     "TRUE" 
# [2,] "FALSE" "0"     "0"     "FALSE"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!