I have a simple R code to add up the components of a 2×2 matrix
sum<-0
for(i in 1:2){ # row
for(j in 1:2){ #column
sum<-sum+mat[i,j]
}
}
Is it possible to use the outer(), or any other function to replace this piece of code and make it more efficient? My aim is to replace nested for loops in my entire code to bring down the time needed to execute my program.
Edit:
I also want to try using it on code snippets like:
for(i in 1:2){ # row
for(j in 1:2){ #coloumn
chisqr<- chisqr+ ((mat[i,j]-expmat[i,j])^2)/expmat[i,j]
}
}
and:
for(i in 1:2){ # row
for(j in 1:2){ #coloumn
rowsum<-0
colsum<-0
for(k in 1:2){
rowsum<- rowsum+mat[i,k]
}
for(k in 1:2){
colsum<- colsum+mat[k,j]
}
expmat[i,j]<- (rowsum*colsum)/sum
}
}
will do the trick. There’s no need for a loop or
outer.Update based on new questions:
You could calculate
expmatusingouter:Afterwards, you could calculate
chisqr:By the way: I recommend having a look at
?chisq.test.