I recently had a problem in which everytime I read a csv file containing a table with values, R read it as a list format instead of numeric. As no thread provided me the entire
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"