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
有一個明顯的贏家。
不適合我! – latorrefabian
>墊< - 基質(1:1000000,NcoI位= 1000) >昏暗(墊) [1] 1000 1000 > object.size(墊) 4000200字節 >模式(墊)< - '整數' > object.size(mat) 4000200 bytes > class(mat [1,]) [1]「integer」 – latorrefabian
R版本3.2.3(2015-12-10) 平臺:x86_64-apple-darwin13.4.0 (64位) 運行於:OS X 10.11.3(El Capitan) – latorrefabian