我的方法并不高雅,但在大量试验中似乎很有效。为了证明这一点,我创建3个功能:F1 - 你的,F2 - joran的,F3 - 雷
library(microbenchmark)
f1 <- function() {
x <- 1:4
y <- 5:8
z <- c(x, y) #edited - previous code read a, b in place of x, y
trials <- 5000
sel <- data.frame()
set.seed(123)
for (i in 1:trials) {
x_sel <- sample(x, 1)
y_sel <- sample(y, 1)
rem <- z[!(z %in% c(x_sel, y_sel))]
z_sel <- sample(rem, 1)
sel <- rbind(sel, cbind(x_sel, y_sel, z_sel))
}
return(sel)
}
f2 <- function() {
set.seed(123)
x <- 1:4
y <- 5:8
z <- c(x, y)
trials <- 5000
xval <- sample(x, size = trials, replace = TRUE)
yval <- sample(y, size = trials, replace = TRUE)
zval <-
mapply(
FUN = function(x, y, z) {
sample(setdiff(z, c(x, y)), 1)
},
x = xval,
y = yval,
MoreArgs = list(z = z)
)
result <- data.frame(xval = xval,
yval = yval,
zval = zval)
return(result)
}
f3 <- function() {
x <- 1:4
y <- 5:8
z <- c(x, y) #edited - previous code read a, b in place of x, y
trials <- 5000
set.seed(123)
x_sel <- sample(x, trials, replace = TRUE)
y_sel <- sample(y, trials, replace = TRUE)
z_mac <- matrix(z,
nrow = trials,
ncol = length(z),
byrow = TRUE)
take <- z_mac != x_sel & z_mac != y_sel
z_sel <- t(matrix(t(z_mac)[t(take)], ncol = trials))
take <- sample(1:ncol(z_sel), size = trials, replace = TRUE)
cbind(x_sel, y_sel, z_sel = z_sel[cbind(1:trials, take)])
}
microbenchmark(f1(), f2(), f3(), times = 10L)
Unit:milliseconds
expr min lq mean median uq max neval
f1() 2193.448113 2248.442450 2258.626023 2258.135072 2267.333956 2346.457082 10
f2() 205.124501 208.672947 213.520267 212.208095 219.397101 222.990083 10
f3() 2.463567 2.491762 2.570517 2.512588 2.603582 2.827863 10
我的F3功能率比F2快f1和83倍的速度856倍。当我们考虑oryginal问题(试验= 5),然后
> microbenchmark(f1(), f2(), f3(), times = 10L)
Unit: microseconds
expr min lq mean median uq max neval
f1() 1215.924 1268.790 1296.7610 1300.5095 1321.015 1370.998 10
f2() 587.937 590.500 619.6248 612.9285 638.881 687.261 10
f3() 68.886 78.819 86.7652 81.2225 91.315 116.947 10
在第3行中,你的意思是写'z < - c(x,y)'? –
是的,我的帖子已被编辑以反映更改。我最初使用a,b和c作为向量,但切换到x,y和z以避免与'c()'函数混淆。不幸的是,我错过了第3行和第10行。 – drumminactuary