user1436187
user1436187

Reputation: 3376

Keep Integer Matrix in R as Integer Matrix

Suppose that I have an integer matrix in R filled with "1".

When I divide it by two it will be converted to a double matrix.

How can I force R to not change the type matrix? (So the matrix will be filled with 0 instead of .5).

It is true that I can use round function later, but it decrease the speed significantly.

Upvotes: 0

Views: 1054

Answers (3)

Dr. Mike
Dr. Mike

Reputation: 2491

Just tell it to keep the integer. It has no effect on your runtime execution.

system.time(mym<-apply(matrix(1,1000,1000), 1:2, function(x) as.integer(x/2)))
# user  system elapsed 
# 4.46    0.01    4.48 
system.time(mym<-apply(matrix(1,1000,1000), 1:2, function(x) x/2))
# user  system elapsed 
# 4.44    0.00    4.46 

So just use the as.integer expression and you keep it an integer.

Upvotes: 0

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32351

You can use Euclidian division, %/%, and make sure you divide by 2L, not 2.

x <- matrix(1L, 5, 5)
str( x %/% 2L )
# int [1:5, 1:5] 0 0 0 0 0 0 0 0 0 0 ...

Upvotes: 1

Msegade
Msegade

Reputation: 488

You can use integer division (%/%) instead of normal division (/):

1%/%2 = 0
1/2=0.5

Upvotes: 1

Related Questions