Say you have a matrix of logical values of size 6x4:
set.seed(4)
mat <- matrix(sample(c(T, F), 24, replace = T), ncol = 4)
mat
# [,1] [,2] [,3] [,4]
# [1,] FALSE TRUE FALSE FALSE
# [2,] TRUE FALSE FALSE TRUE
# [3,] TRUE TRUE FALSE TRUE
# [4,] TRUE FALSE FALSE TRUE
# [5,] TRUE TRUE FALSE TRUE
# [6,] FALSE FALSE TRUE TRUE
How would you coerce this to be a matrix of data of a different class? For example, if you want it to be integers, such that FALSE
is coerced to 0
and TRUE
is coerced to 1
, you might try as.integer
:
as.integer(mat)
# [1] 0 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 1 0 1 1 1 1 1
That doesn't work as it also turns the matrix into a 1-dimensional vector. You might then rebuild a matrix of the same size, but this seems like an inelegant or indirect approach. Can you coerce the data in the matrix into another class without having to rebuild the matrix?
matrix(as.integer(mat), ncol = ncol(mat))
# [,1] [,2] [,3] [,4]
# [1,] 0 1 0 0
# [2,] 1 0 0 1
# [3,] 1 1 0 1
# [4,] 1 0 0 1
# [5,] 1 1 0 1
# [6,] 0 0 1 1
You can use storage.mode <-
:
Get or set the ‘mode’ (a kind of ‘type’), or the storage mode of an R object.
storage.mode(mat) <- "integer"
storage.mode(mat) <- "numeric"
storage.mode(mat) <- "character"
(however, trying to convert to character
and then back to logical
will fail ...)