File: sample.simple.R

package info (click to toggle)
r-cran-animation 2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,268 kB
  • sloc: javascript: 873; sh: 15; makefile: 2
file content (37 lines) | stat: -rw-r--r-- 1,474 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#' Demonstration for simple random sampling without replacement
#'
#' The whole sample frame is denoted by a matrix (\code{nrow * ncol}) in the
#' plane just for convenience, and the points being sampled are marked out (by
#' red circles by default). Each member of the population has an equal and known
#' chance of being selected.
#' @param nrow the desired number of rows of the sample frame.
#' @param ncol the desired number of columns of the sample frame.
#' @param size the sample size.
#' @param p.col,p.cex different colors /magnification rate to annotate the
#'   population and the sample
#' @return None (invisible \code{NULL}).
#' @author Yihui Xie
#' @references Examples at \url{https://yihui.org/animation/example/sample-simple/}
#' @seealso \code{\link{sample}}, \code{\link{sample.ratio}},
#'   \code{\link{sample.cluster}}, \code{\link{sample.strat}},
#'   \code{\link{sample.system}}
#' @export
sample.simple = function(
  nrow = 10, ncol = 10, size = 15, p.col = c('blue', 'red'), p.cex = c(1, 3)
) {
  if (size > nrow * ncol)
    stop('sample size must be smaller than the population')
  x = cbind(rep(1:ncol, nrow), gl(nrow, ncol))
  nmax = ani.options('nmax')
  for (i in 1:nmax) {
    dev.hold()
    plot(
      x, pch = 19, col = p.col[1], cex = p.cex[1], axes = FALSE, ann = FALSE,
      xlab = '', ylab = ''
    )
    points(x[sample(nrow * ncol, size), ], col = p.col[2], cex = p.cex[2])
    box(lwd = 1)
    ani.pause()
  }
  invisible(NULL)
}