您可以使用 switch
,findInterval
和其中一个do.call
或的组合mapply
。
您使用哪个可能取决于您希望输出的排序方式
设置开关
A <- 0.423
B <- 0.324
C <- 0.253
interval <- c(0, cumsum(c(A, B, C)))
random <- runif(50, 0, 1)
rnorm_vals <- function(interval) {
switch(interval, `1` = list(mean = 25, sd = 4), `2` = list(mean = 25, sd = 4.5),
`3` = list(mean = 30, sd = 5))
}
intervals <- findInterval(random, interval, rightmost.closed = T, all.inside = T)
how_many <- table(intervals)
rnorm_calls <- lapply(names(how_many), function(nm) {
do.call(rnorm, c(n = how_many[[nm]], rnorm_vals(nm)))
})
rnorm_calls
## [[1]]
## [1] 28.38 18.54 20.52 25.79 27.50 36.86 23.40 20.82 23.75 30.64 27.62
## [12] 20.23 24.21 22.21 20.16 21.73 29.96 27.28 25.68
##
## [[2]]
## [1] 24.91 30.90 30.35 26.08 18.74 27.33 23.29 33.80 30.37 27.49 36.78
## [12] 23.03 24.66 21.46 22.62 33.32 16.16
##
## [[3]]
## [1] 30.62 29.50 31.19 25.07 24.68 33.25 40.04 33.42 30.81 21.48 32.79
## [12] 25.56 30.98 30.16
##
# or (will be sorted by )
unlist(rnorm_calls)
## [1] 28.38 18.54 20.52 25.79 27.50 36.86 23.40 20.82 23.75 30.64 27.62
## [12] 20.23 24.21 22.21 20.16 21.73 29.96 27.28 25.68 24.91 30.90 30.35
## [23] 26.08 18.74 27.33 23.29 33.80 30.37 27.49 36.78 23.03 24.66 21.46
## [34] 22.62 33.32 16.16 30.62 29.50 31.19 25.07 24.68 33.25 40.04 33.42
## [45] 30.81 21.48 32.79 25.56 30.98 30.16
使用映射
或者你可以扫过并接到 rnorm 的单个电话
rnorm_details <- lapply(intervals, rnorm_vals)
means <- sapply(rnorm_details, `[[`, "mean")
sds <- sapply(rnorm_details, `[[`, "sd")
mapply(rnorm, n = 1, sd = sds, mean = means)
## [1] 24.70 24.33 36.22 21.87 25.40 18.39 23.54 26.90 25.81 17.35 19.45
## [12] 18.53 33.88 27.51 21.70 25.06 24.17 35.08 28.24 21.88 29.90 28.18
## [23] 29.08 24.54 30.43 29.27 28.79 22.09 20.77 18.82 21.73 22.99 26.69
## [34] 27.73 26.66 25.32 29.95 30.77 34.89 28.55 22.95 32.45 36.11 29.72
## [45] 39.23 22.39 26.78 23.36 18.06 33.39