Reputation: 59
I have a double loop in this form:
for (j in 1:col(mat))
{
for (i in 1:nrow(mat))
{
decision[i][j] = ifelse(mat[i][j] > 3, 1, 0)
}
}
Is there any way this functionality can be achieved through one of the apply functions with significantly improved speed?
Upvotes: 0
Views: 78
Reputation: 6355
R is a vectorized language, so for this kind of simple manipulation of a matrix apply
type functions are not needed, just do:
decision <- ifelse(mat > 3, 1, 0)
(I'm assuming you want to iterate through the elements of the matrix, which means you would say ncol(mat)
in your loop; col
gives something rather different).
Upvotes: 1
Reputation: 206167
You don't need any loops. If you create a matrix that looks like this
mat<-matrix(sample(1:10, 5*7, replace=T), ncol=7)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#[1,] 9 6 10 7 6 10 6
#[2,] 7 6 3 3 6 8 3
#[3,] 7 9 7 5 6 7 6
#[4,] 2 3 8 6 10 1 5
#[5,] 4 1 5 6 1 10 6
then you can just do
decision <- (mat>3)+0
decision;
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#[1,] 1 1 1 1 1 1 1
#[2,] 1 1 0 0 1 1 0
#[3,] 1 1 1 1 1 1 1
#[4,] 0 0 1 1 1 0 1
#[5,] 1 0 1 1 0 1 1
Upvotes: 2