尝试这个:
D <- (A < 8) * B + (A >= 8) * C
它有点快:
A = matrix(sample(16,1e4,TRUE),100,100)
B = matrix(rnorm(1e4,5,1),100,100)
C = matrix(rnorm(1e4,9,1),100,100)
require(microbenchmark)
microbenchmark(D1 <- (A < 8) * B + (A >= 8) * C, D2 <- ifelse(A<8,B,C))
Unit: microseconds
expr min lq median uq max neval
D1 <- (A < 8) * B + (A >= 8) * C 499.102 528.4075 542.2415 554.983 674.206 100
D2 <- ifelse(A < 8, B, C) 4015.024 4062.5310 4079.4590 4173.564 5512.694 100
identical(D1,D2)
[1] TRUE
编辑:它可以变得更快:
D <- {A < 8} * {B - C} + C
注意花括号而不是括号和单个比较。基准测试:
microbenchmark(D1 <- {A < 8} * {B - C} + C, D2 <- ifelse(A<8,B,C))
Unit: microseconds
expr min lq median uq max neval
D1 <- { A < 8 } * { B - C } + C 289.050 300.881 310.7105 333.645 496.189 100
D2 <- ifelse(A < 8, B, C) 4027.037 4057.980 4069.8110 4148.627 5372.173 100
sum(abs(D1-D2))
#[1] 8.304468e-14
但是考虑到C
.