来自三角分布的随机样本:R

A random sample from triangular distribution: R

我想从具有三个参数的三角分布生成数字:a、b、c,其中 c 在我的例子中定义为 (a+b)/2。 假设我有一个向量 x:

x <- c(1,-1,2,-2,3,-3,4,-4,5,-5,11,-11,12,-12,13,-13)

我想生成与向量 x 中的负数一样多的新值。因此,我可以进一步用三角分布生成的数字替换负值。

library(triangle)
c = abs(x[x<0])/2
sample <- rtriangle(length(a[which(a<0)]), 0, abs(x[x<0]),c)

显然这不起作用,因为我收到一条警告消息:

Warning messages: 1: In if (a > c | b < c) return(rep(NaN, times = n)) : the condition has length > 1 and only the first element will be used 2: In if (a != c) { : the condition has length > 1 and only the first element will be used 3: In p[i] * (b - a) : longer object length is not a multiple of shorter object length 4: In p[i] <- a + sqrt(p[i] * (b - a) * (c - a)) : number of items to replace is not a multiple of replacement length 5: In (1 - p[j]) * (b - a) : longer object length is not a multiple of shorter object length 6: In p[j] <- b - sqrt((1 - p[j]) * (b - a) * (b - c)) : number of items to replace is not a multiple of replacement length

由于 rtriangle 不将向量作为输入,您可以使用 sapply 创建一个向量来评估向量的每个元素,如下所示:

x <- c(1,-1,2,-2,3,-3,4,-4,5,-5,11,-11,12,-12,13,-13)

library("triangle")

sample = sapply(abs(x[x<0]), function(x){ rtriangle(1,0,x,x/2) })

> sample
[1] 0.6514940 0.6366981 1.8598445 0.9866790 1.7517438 2.9444719 4.1537113 2.2315813

您将获得 8 种不同三角分布的随机样本。