Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't coerce class of matrix numbers to integer

Tags:

oop

class

r

matrix

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!

like image 910
isomorphismes Avatar asked Sep 07 '12 22:09

isomorphismes


2 Answers

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 ...
like image 88
Joshua Ulrich Avatar answered Sep 21 '22 18:09

Joshua Ulrich


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.

like image 45
rapture Avatar answered Sep 21 '22 18:09

rapture