tprebyl
tprebyl

Reputation: 43

R loop replace multiple values in matrix

does anyone know a more efficient way to do the following? I have two matrices, one with integer values, the other with numeric. I also have a list containing integer vectors. I have a loop which sets the values of the numeric matrix to NA, when the integer values from the list are equal to the integer matrix. Then I get the row product and sum from the resulting matrix. Is there a way to avoid creating a copy of the numeric matrix each step? Or perhaps another approach all together? Thanks

mat1<-matrix(rpois(20*300000,6),20,300000)
mat2<-matrix(runif(20*300000),20,300000)
list1<-list(c(1,2,3),c(4,6),c(8,9,10,11))
results<-vector('numeric',length(list1))

start.time=Sys.time()
for(i in 1:length(list1)){
    copy<-mat2
    copy[mat1 %in% list1[[i]]]=NA
    results[i]=sum(apply(copy,2,prod,na.rm=T))
}
print(Sys.time()-start.time)
#

Upvotes: 2

Views: 2044

Answers (1)

eddi
eddi

Reputation: 49448

Replacing your apply with colSums (assuming your numbers are positive, you'll need a bit more fiddling otherwise) gives me a close to 2x speed improvement:

for(i in 1:length(list1)){
    copy<-mat2
    copy[mat1 %in% list1[[i]]]=NA
    results[i]=sum(exp(colSums(log(copy), na.rm = T)))
}

Upvotes: 1

Related Questions