Skip to content

Instantly share code, notes, and snippets.

@gregorp
Last active August 29, 2015 13:56
Show Gist options
  • Save gregorp/9331642 to your computer and use it in GitHub Desktop.
Save gregorp/9331642 to your computer and use it in GitHub Desktop.
samp functions for small random subsets
#' Sample of an object.
#'
#' Shortcut for checking on data.
#' @rdname samp
#' @param x data.frame (or matrix) to sample from
#' @param n number of rows to sample (default is 10)
#' @return n random rows of x
#' @export
samp <- function(x, n) {
UseMethod("samp")
}
#' @rdname samp
#' @method samp data.frame
#' @S3method samp data.frame
samp.data.frame <- function(x, n = 10) {
if (n > nrow(x)) {
warning("samp: object smaller than sample size, whole object returned.")
return(x)
}
x[sample(nrow(x), size = n), ]
}
#' @rdname samp
#' @method samp matrix
#' @S3method samp matrix
samp.matrix <- function(x, n = 10) {
if (n > nrow(x)) {
warning("samp: object smaller than sample size, whole object returned.")
return(x)
}
x[sample(nrow(x), size = n), ]
}
#' @rdname samp
#' @method samp default
#' @S3method samp default
samp.default <- function(x, n = 10) {
if (n > length(x)) {
warning("samp: object smaller than sample size, whole object returned.")
return(x)
}
x[sample(length(x), size = n)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment