Home > database >  Generate random decimal numbers with given mean in given range in R
Generate random decimal numbers with given mean in given range in R

Time:10-16

Hey I want to generate 100 decimal numbers in the range of 10 and 50 with the mean of 32.2.

I can use this to generate the numbers in the wanted range, but I don't get the mean:

runif(100, min=10, max=50)

Or I could use this and I dont get the range:

rnorm(100,mean=32.2,sd=10)

How can I combine those two or can I use another function?

I have tried to use this approach: R - random distribution with predefined min, max, mean, and sd values But I dont get the exact mean I want... (31.7 in my example try)

n <- 100
y <- rgbeta(n, mean = 32.2, var = 200, min = 10, max = 50)

Edit: Ok i have lowered the var and the mean gets near to 32.2 but I still want some values near the min and max range...

CodePudding user response:

This isn't perfect, but maybe its a start. I can't get the range to work out perfectly, so I just played with the "max" until I got an output I was happy with. There is probably a more solid math way to do this. The result is uniform-adjacent... at best...

rand_unif_constrained <- function(num, min, max, mean) {
  vec <- runif(num, min, max)
  vec / sum(vec) * mean*num
}


set.seed(35)
test <- rand_unif_constrained(100, 10, 40, 32.2) #play with max until max output is less that 50

mean(test)
#> [1] 32.2
min(test)
#> [1] 12.48274
max(test)
#> [1] 48.345


hist(test)

CodePudding user response:

In order to get random numbers between 10 and 50 with a (true) mean of 32.2, you would need a density function that would fulfill those properties.

A uniform distribution with a min of 10 and a max of 50 (runif) will never deliver you that mean, as the true mean is 30 for that distribution.

The normal distribution has a range from - infinity to infinity, independent of the mean it has, so runif will return numbers greater than 50 and smaller than 10.

You could use a truncated normal distribution

rnormTrunc(n = 100, mean = 32.2, sd = 1, min = 10, max = 50),

if that distribution would be okay. If you need a different distibution, things will get a little more complicated.

Edit: feel free to ask if you need the math behind that, but depending on what your density function should look like it will get very complicated

  • Related