【问题标题】:R - random numbers in a similar distribution to real numbersR - 与实数分布相似的随机数
【发布时间】:2013-03-19 16:05:16
【问题描述】:

这是一个非常简化的示例,但希望它能让每个人都明白我在说什么:

real.length = c(10,11,12,13,13,13,13,14,15,50)

random.length = vector() 
for (i in 1:length(real.length)){
    random.length[i] = sample(min(real.length):max(real.length),1)
}

(注意:我知道我可以说 random.length=sample(min:max,10) 但我需要在我的真实代码中使用循环。)

我希望我的随机长度与我的实际长度具有相似的范围,但分布也相似。我试过 rnorm 但我的真实数据没有正态分布,所以我认为除非有一些我错过的选项,否则我认为这不会起作用。

是否可以使用我的真实数据设置示例函数的概率?因此,在这种情况下,为 10-15 之间的数字赋予较高的权重/概率,而为 50 等高数赋予较低的权重/概率。

编辑:使用詹姆斯的解决方案:

samples = length(real.length) 
d = density(real.length)
random.length = d$x[findInterval(runif(samples+100),cumsum(d$y)/sum(d$y))]
random.length = subset(random.length, random.length>0)
random.length = random.length[1:samples]

【问题讨论】:

  • 您是否希望能够返回 [10 11 12 13 14 15 50} 以外的值?换句话说 - 您是否试图找到一个平滑的 PDF 来近似您观察到的频率(尽管其他值可能是可能的,例如 45),或者观察到的频率是您想要采样的 only 频率吗?后者比前者容易得多...
  • 不幸的是,前者听起来更像它——所以我很乐意生成一个看起来有点像 [10 10 11 14 14 15 15 16 48 49] 的 random.length

标签: r random distribution sample weighted


【解决方案1】:

您可以创建一个density 估计并从中采样:

d <- density(real.length)
d$x[findInterval(runif(6),cumsum(d$y)/sum(d$y))]
[1] 13.066019 49.591973  9.636352 15.209561 11.951377 12.808794

请注意,这假设您的变量是连续的,所以round 是您认为合适的。

【讨论】:

  • 这绝对是正确的——谢谢。但是,当我从正确的数据 min = -441268 中尝试时,我的很多长度现在都是负数,这显然是不正确的。不过,分布看起来好多了。
  • @JessicaB 只是将负数子集化(可能它们是错误的)
【解决方案2】:

虽然我可以阅读R,但我不会写它(我没有安装它,所以无法测试)。我将在 Matlab 中给你一个简单的例子,它会像你问的那样做 - 我希望这能激励你:

obs = sort([10 11 12 13 13 13 13 14 15 50]); % have to make sure they are sorted...
uo = unique(obs);
hh = hist(obs, uo); % find frequencies of each value
cpdf = cumsum(obs);
cpdfn = cpdf / max(cpdf); % normalized cumulative pdf
r = rand(1, 100); % 100 random numbers from 0 to 1
rv = round(interp1(cpdfn, uo, r)); % randomly pick values in the cpdfn; find corresponding "observation"
hr = hist(rv, 1:50);
hrc = cumsum(hr);
figure
plot(uo, cpdfn);
hold all;
plot(1:50, hhc/max(hhc))

figure; hist(rv, 1:50);

这会产生以下图:

注意 - 当你有更多的观察时,这会更好;在当前示例中,由于您的样本相对较少,因此 15 到 50 之间的空间在大约 10% 的时间内被采样。

【讨论】:

  • 谢谢!乍一看,这似乎是一个很酷的解决方案,我从未使用过 Matlab,但是当我有时间时,这会很有趣 - 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2016-11-09
  • 2014-08-04
  • 2010-09-16
  • 2016-02-28
  • 1970-01-01
  • 2010-11-06
相关资源
最近更新 更多