Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R使用apply避免for循环_R_For Loop_Apply - Fatal编程技术网

R使用apply避免for循环

R使用apply避免for循环,r,for-loop,apply,R,For Loop,Apply,我有这样的问题。我用这种说法来解决问题,但速度太慢了。我可以使用apply函数提高性能吗 x<-matrix(sample(1:100,40),20,2) x<-as.data.frame(x) for ( i in 1:nrow(x)) { if ( x[i,1]>x[i,2] ){ x[i,3]<-1 } else { x[i,3]<-0 } } x您不需要显式或隐式循环;只需使用ifelse: x[, 3] <- ifels

我有这样的问题。我用这种说法来解决问题,但速度太慢了。我可以使用apply函数提高性能吗

x<-matrix(sample(1:100,40),20,2)
x<-as.data.frame(x)
for ( i in 1:nrow(x))
{
  if ( x[i,1]>x[i,2] ){
    x[i,3]<-1
  } else {
    x[i,3]<-0
  }
}

x您不需要显式或隐式循环;只需使用
ifelse

x[, 3] <- ifelse(x[, 1] > x[, 2], 1, 0)
x[,3]x[,2],1,0)
事实上,你可以进一步简化:

x[, 3] <- x[, 1] > x[, 2]
x[,3]x[,2]
这将创建一个逻辑列,而不是数字列,但对于大多数目的来说,这已经足够接近了。如果不是,则可以将逻辑值转换回数字:

x[, 3] <- as.numeric(x[, 1] > x[, 2])
x[,3]x[,2])

在我的机器上,速度大约快10倍