Ville
Ville

Reputation: 547

Generating rnorm() data within a range

How can I generate randomly distributed data within a rage of 10-15? I tried this but, most of the data are just 10s.

library(MCMCglmm)

x=matrix(rtnorm(n = 100, lower = 10, upper = 15), nrow=10, ncol=10)

Here's a part of the matrix:

        [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]     [,9]    [,10]
 [1,] 10.01323 10.09077 10.12173 10.21363 10.14710 10.07159 10.19811 10.16515 10.14877 10.13405
 [2,] 10.10269 10.08853 10.07679 10.21932 10.15413 10.00907 10.00788 10.06476 10.06058 10.09998
 [3,] 10.00339 10.02658 10.05871 10.03135 10.07163 10.03250 10.08346 10.17975 10.10160 10.12360
 [4,] 10.00334 10.07949 10.00456 10.04519 10.11282 10.06135 10.05492 10.10164 10.13717 10.00696
 [5,] 10.12996 10.07651 10.25793 10.10667 10.14016 10.02615 10.02722 10.16351 10.28760 10.06861

As seen most of the data are 10s no 15s.

Upvotes: 1

Views: 1823

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226182

You probably want to change the mean to be in the middle of the range; it's zero by default.

library(MCMCglmm)
set.seed(101)
par(mfrow=c(1,2))
hist(rtnorm(1e5,lower=10,upper=15),col="gray",main="mean=0")
hist(rtnorm(1e5,mean=12.5,lower=10,upper=15),col="gray",main="mean=12.5")

enter image description here

In answer to your revised question, maybe

rtnorm(n, mean = x%*%beta+8, sd = 2, lower=10, upper=15)

will work.

Upvotes: 4

Related Questions