You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Base R中实现指定非均匀概率的0-1区间随机抽样?

How to Sample from Mixed Uniform Intervals in Base R

Great question—your initial approach hits a common snag: instead of sampling from the two intervals with your desired probabilities, you're creating a weighted average of two uniform samples. That's why you can't get values like 0.8: the maximum possible value from your code is 0.9*0.3 + 0.1*1 = 0.37, which doesn't even reach the upper half of your second interval!

Luckily, Base R has simple, straightforward ways to do this correctly. Here are a few options:

Option 1: Conditional Sampling (Readable for Single Samples)

First pick which interval to sample from using the specified probabilities, then draw a uniform value from that interval:

# Choose the interval
which_interval <- sample(c("low", "high"), size = 1, prob = c(0.9, 0.1))

# Draw the sample
if (which_interval == "low") {
  runif(1, min = 0, max = 0.3)
} else {
  runif(1, min = 0.3, max = 1)
}

Option 2: One-Liner with ifelse (Quick Single Samples)

For a more concise version, use ifelse to check a uniform probability trigger:

ifelse(runif(1) < 0.9, runif(1, 0, 0.3), runif(1, 0.3, 1))

Option 3: Vectorized Approach (Efficient for Multiple Samples)

If you need to generate many samples at once, this vectorized method is faster than looping:

n_samples <- 1000  # Adjust to your needs
samples <- numeric(n_samples)

# Mark which samples come from the low interval
low_samples <- runif(n_samples) < 0.9

# Fill in samples from each interval
samples[low_samples] <- runif(sum(low_samples), 0, 0.3)
samples[!low_samples] <- runif(sum(!low_samples), 0.3, 1)

All of these methods ensure that 90% of your samples come directly from the 0–0.3 range, and 10% come directly from 0.3–1—so you'll absolutely get values like 0.8 when the second interval is selected.

内容的提问来源于stack exchange,提问作者Omry Atia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:50