Skip to content

Commit

Permalink
prevent specifying the same column name twice in a piped data.frame
Browse files Browse the repository at this point in the history
closes #47
  • Loading branch information
sfirke committed Sep 8, 2016
1 parent 88d3fad commit c72da11
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
5 changes: 3 additions & 2 deletions R/crosstab.R
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ crosstab <- function(...) UseMethod("crosstab")
#' @describeIn crosstab Create a crosstab from two vectors.
#' @export
crosstab.default <- function(vec1, vec2, percent = "none", show_na = TRUE, ...){

if(!mode(vec1) %in% c("logical", "numeric", "character", "list") | is.matrix(vec1)){
stop("vec1 must be a vector of type logical, numeric, character, list, or factor")}
if(!mode(vec2) %in% c("logical", "numeric", "character","list") | is.matrix(vec2)){
Expand Down Expand Up @@ -110,7 +110,8 @@ crosstab.data.frame <- function(.data, ...){

# select columns from .data
columns <- dots[1:2]

if(dots[[1]] == dots[[2]]){stop("the same column name is specified for both input variables. Use tabyl() for tabulating a single variable")}

x <- list()
x[[deparse(columns[[1]])]] <- .data[,deparse(columns[[1]])]
x[[deparse(columns[[2]])]] <- .data[,deparse(columns[[2]])]
Expand Down
1 change: 1 addition & 0 deletions tests/testthat/test-crosstab.R
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ test_that("bad inputs are handled properly", {
expect_error(crosstab(c(1,2), complex(1:2), complex(1:2)), "vec2 must be a vector of type logical, numeric, character, list, or factor")
expect_error(crosstab(c(1,2), c(1:2), "blargh"), "'percent' must be one of 'none', 'row', 'col', or 'all'")
expect_error(crosstab(c(1, 1), c(1)), "the two vectors are not the same length")
expect_error(mtcars %>% crosstab(cyl, cyl), "the same column name is specified for both input variables. Use tabyl() for tabulating a single variable", fixed = TRUE)
})

# simple crosstab w/o NAs
Expand Down

0 comments on commit c72da11

Please sign in to comment.