简体   繁体   English

在R中套用功能族

[英]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: R是向量化语言,因此对于这种对矩阵的简单操作,不需要apply类型函数,只需执行以下操作:

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). (我假设您要遍历矩阵的元素,这意味着您将在循环中说ncol(mat)col给出了一些完全不同的东西)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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