I'm writing an adjacency matrix in R
like so:
neighbours <- array(0, c(100,100))
for (i in 1:100) { neighbours[i,i] = 1 } #reflexive
But then I notice that the class(neighbours)
is double matrix
. That's going to take up way too much room with a larger matrix. So I want to coerce the type to integer
or, even better, since this is undirected, logical
.
But...
> class(neighbours[5])
[1] "numeric"
> class(neighbours[5]) <- "integer"
> class(neighbours[5])
[1] "numeric"
It is no listen to me!
It's better to not initialize it as numeric in the first place, but if you can't do that, set the storage.mode
:
R> neighbours <- array(0, c(100,100))
R> for (i in 1:100) { neighbours[i,i] = 1 }
R> str(neighbours)
num [1:100, 1:100] 1 0 0 0 0 0 0 0 0 0 ...
R> storage.mode(neighbours) <- "integer"
R> str(neighbours)
int [1:100, 1:100] 1 0 0 0 0 0 0 0 0 0 ...
R> storage.mode(neighbours) <- "logical"
R> str(neighbours)
logi [1:100, 1:100] TRUE FALSE FALSE FALSE FALSE FALSE ...
For those who are still looking for a method to coerce an existing numeric matrix to an integer one:
m2 <- apply (m, c (1, 2), function (x) {
(as.integer(x))
})
The c(1, 2) means apply the function to rows and columns. Testing the class of the elements then gives:
> class(m2[1,])
[1] "integer"
> class(m[1,])
[1] "numeric"
>
I was looking for something like this because I needed to convert an already existing numerical matrix. It was the result of a very slow computation so modifying the code would have taken me much more time than simply converting the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With