Is it possible to sample real numbers with the sample() function? (I.e., sample from a continuous distribution, e.g. [1,10] so that when I sample I won't get an integer but a real number, e.g 5.467.)
If not, is there another function to do that?
Is it possible to sample real numbers with the sample() function? (I.e., sample from a continuous distribution, e.g. [1,10] so that when I sample I won't get an integer but a real number, e.g 5.467.)
If not, is there another function to do that?
The purpose of sample is to... well sample, uniformly or not, with replacement or not, from a finite set.
If you want a sample from another kind of distribution, it depends on the distribution, and there are many functions in R to achieve that. The most common are runif (uniform distribution on a bounded interval) and rnorm (the normal distribution).
See ?sample and ?Distributions in the documentation. A more comprehensive list can be found here.
For instance:
Uniform sample with replacement, from {1, 2, 3, 4}:
> sample(1:4, 10, replace=T)
[1] 3 1 4 1 2 1 1 3 4 3
Uniform sample from [0, 1]:
> runif(10)
[1] 0.6529710 0.1977511 0.7946746 0.6351793 0.9518663
0.9356524 0.2945506 0.4623502 0.8198065 0.8516961
Normal sample with mean 0 and variance 1:
> rnorm(10)
[1] -1.13195127 0.43434313 -0.44183752 0.13632993 0.75902968
0.76079877 0.37919727 0.41350485 0.76233633 0.09400158
These functions can take parameters: runif(n, a, b) yields n samples from the interval [a, b] for instance.