Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disallow indexing by factors #24

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export(strict_diag)
export(strict_drop)
export(strict_sample)
export(strict_sapply)
export(strict_square_bracket)
import(rlang)
38 changes: 38 additions & 0 deletions R/shim-square-bracket.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
register_shims_square_bracket <- function(env) {
rlang::env_bind(env,
`[` = strict_square_bracket
)
}

#' Strict behaviour for square bracket indexing
#'
#' The effect of indexing with a factor is unclear, since factors can behave
#' like character vectors or integer vectors, depending upon context. In
#' strict mode, factor indexing throws an error.
#'
#' @param x The object to be indexed.
#' @param ... Indexing values.
#' @export
#' @examples
#' (x <- c(d = 1, c = 4, b = 9, a = 16))
#' (index <- factor(letters[1:4]))
#' # Character and integer indexing is OK.
#' x[as.character(index)]
#' x[as.integer(index)]
#' # Factor indexing is disallowed.
#' try(x[index])
#'
#' # For higher dimension objects, passing a factor
#' # to any dimension throws an error.
#' d <- data.frame(
#' a = 1:4, b = letters[1:4], c = runif(4),
#' stringsAsFactors = FALSE)
#' try(d[factor(d$b), ])
#' try(d[, factor(c("a", "b"))])
strict_square_bracket <- function(x, ...) {
indexers <- rlang::dots_list(..., .ignore_empty = "all")
if (any(vapply(indexers, is.factor, logical(1L)))) {
stop("Indexing with a factor has unclear behavior. Explicitly coerce your index to a character or integer vector.")
} else base::`[`(x, ...)
}

1 change: 1 addition & 0 deletions R/shims.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ register_shims <- function() {
register_shims_apply(strict_shims)
register_shims_risky(strict_shims)
register_shims_scalar(strict_shims)
register_shims_square_bracket(strict_shims)
}

register_shim_T_F <- function(env) {
Expand Down
35 changes: 35 additions & 0 deletions man/strict_square_bracket.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.