Skip to content

Instantly share code, notes, and snippets.

@smbache
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smbache/245aae6dafc5c6b6dbec to your computer and use it in GitHub Desktop.
Save smbache/245aae6dafc5c6b6dbec to your computer and use it in GitHub Desktop.
A loggr example
library(loggr) # should be executed before sourcing the script
log_file("all.log")
log_file("messages.log", DEBUG, INFO, .warning = FALSE, .error = FALSE)
log_file("console", WARN, ERROR, CRITICAL, .message = FALSE)
top_n <- function(data_set, sort_var, n = 3, desc = FALSE)
{
if (!is.data.frame(data_set))
log_critical("Invalid data_set provided.")
if (!is.character(sort_var) || !sort_var %in% names(data_set))
log_critical("Invalid column for sorting.")
if (NROW(data_set) < n) {
log_warn("Not enough rows in data set. Returning all rows.")
return(data_set)
}
msg <- sprintf("Received %d rows. Selecting top %d according to %s (%s).",
NROW(data_set),
n,
sort_var,
if (desc) "descending" else "ascending")
log_info(msg)
idx <- order(data_set[[sort_var]], decreasing = desc)
head(data_set[idx, ], n)
}
top_n(iris, "Sepal.Width", 3)
top_n(iris, "Sepal.Width", 3, desc = TRUE)
top_n(iris[1:3, ], "Sepal.Width", 5)
top_n(1:10, "nosuch", 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment