简体   繁体   中英

Apply family of functions in R

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?

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM