2016-04-29 824 views
2

我剛剛意識到,如果您創建一個具有整數值的矩陣,它們將存儲爲數字。將矩陣強制轉換爲整數矩陣的最快方法R

a <- matrix(c(0,1,0,1), ncol=2) 
class(a[1,]) # numeric 

整數矩陣需要一半的內存量(對於大尺寸)。 下面的函數強制將所有值整數:

forceMatrixToInteger <- function(m){ 
    apply (m, c (1, 2), function (x) { 
     (as.integer(x)) 
    }) 
} 

a <- forceMatrixToInteger(a) 

class(a[1,]) # integer 

我想知道,如果你能想到的任何其他方式做到這一點,如果它會更快或更高效的內存。

sessionInfo

R version 3.2.3 (2015-12-10) 
Platform: x86_64-apple-darwin13.4.0 (64-bit) 
Running under: OS X 10.11.3 (El Capitan) 

編輯:第一個測試

我定義的函數,它理查德·斯克裏答案描述,我定義的,和測試速度。

exp_size <- 4 
exp_reps <- 3 
mat <- matrix(sample(c(0,1), 10^exp_size, replace=TRUE),ncol=10^(exp_size/2)) 

fun1<-function(){ 
    mode(mat) <- 'integer' 
} 

time <- proc.time() 
    for (i in 1:10^exp_reps){ 
    fun1() 
} 
time <- proc.time()-time 
print('Results fun1:') 
print(time) 

print(time) 
# user system elapsed 
# 0.096 0.035 0.132 

fun2 <- function(){ 
    apply (mat, c (1, 2), function (x) { 
     (as.integer(x)) 
    }) 
} 

time <- proc.time() 
for (i in 1:10^exp_reps){ 
    fun2() 
} 
time <- proc.time()-time 
print('Results fun2:') 
print(time) 

# user system elapsed 
# 22.592 0.148 22.775 

有一個明顯的贏家。

回答

6

如果你做c(0, 1, 0, 1),看起來你會創建整數,但你實際上創造了一個雙打矢量。對於整數,你將不得不使用c(0L, 1L, 0L, 1L)rep(0:1, 2)(因爲:創建一個整數向量)。要將矩陣更改爲整數,可以更改其內部存儲模式。

a <- matrix(c(0,1,0,1), ncol=2) 
object.size(a) 
# 232 bytes 
mode(a) <- "integer" 
object.size(a) 
# 216 bytes 

我不知道它有多快,但它很容易。

+0

不適合我! – latorrefabian

+0

>墊< - 基質(1:1000000,NcoI位= 1000) >昏暗(墊) [1] 1000 1000 > object.size(墊) 4000200字節 >模式(墊)< - '整數' > object.size(mat) 4000200 bytes > class(mat [1,]) [1]「integer」 – latorrefabian

+0

R版本3.2.3(2015-12-10) 平臺:x86_64-apple-darwin13.4.0 (64位) 運行於:OS X 10.11.3(El Capitan) – latorrefabian