set.seed(10)
A <- matrix(round(rnorm(5000*3000,100),1),5000,3000)
afun <- function(x){
if(x > 100){
y = 100*x
}else if(x < 0){
y = -x
}else{
y = x + 50
}
return(y)
}
cfun <- function(x){
id1 = x>100
id2 = x<0
id3 = (x>=0 & x<= 100)
x[id1] = x[id1]*100
x[id2] = -x[id2]
x[id3] = x[id3] + 50
return(x)
}
system.time((ha = apply(A,c(1,2),afun)))
system.time((hc = apply(A,2,cfun)))
> system.time((ha = apply(A,c(1,2),afun)))
用户 系统 流逝
33.62 0.39 34.05
>
> system.time((hc = apply(A,2,cfun)))
用户 系统 流逝
0.69 0.00 0.69
在你这种情况,第二种方法会快得多