Skip to content

Instantly share code, notes, and snippets.

@gertvv
Created July 31, 2013 12:25
Show Gist options
  • Save gertvv/6121549 to your computer and use it in GitHub Desktop.
Save gertvv/6121549 to your computer and use it in GitHub Desktop.
Check dynamic matrix indexing in R code. Sometimes, an expression like m[i:j, ] will return a matrix (when i != j) and otherwise a vector. This is a source of bugs in much of my R code. m[i:j, , drop=FALSE] explicitly disables this behavior. This gist contains R code to check your R code for matrix indexing operations that don't have drop= speci…
library(codetools)
addMatrixHandler <- function(fn) {
addCollectUsageHandler('[', 'base', fn)
}
myMatrixHandler <- function(e, w) {
w$enterGlobal("function", "[", e, w)
if (length(e) > 3 && !('drop' %in% names(e))) {
simple <- sapply(dropMissings(e[-(1:2)]), function(a) {
length(a) == 1 && !is.symbol(a) &&
(is.numeric(a[[1]]) || is.character(a[[1]]))
})
if(!all(simple)) {
w$signal(
paste("Indexing a matrix, but not specifying 'drop' in",
pasteExpr(e)),
w)
}
}
for (a in dropMissings(e[-1])) walkCode(a, w)
}
env <- getNamespace("codetools")
environment(addMatrixHandler) <- env
environment(myMatrixHandler) <- env
addMatrixHandler(myMatrixHandler)
# To check a single function:
# checkUsage(fn)
# To check a package:
# library(pkgName); checkUsagePackage('pkgName')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment