Skip to content

Commit

Permalink
Merge pull request #182 from RomanTsegelskyi/empty_fix
Browse files Browse the repository at this point in the history
fix #180 for empty objects
  • Loading branch information
daroczig committed Jun 11, 2015
2 parents b048efb + 678c21b commit 6d324f6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
14 changes: 11 additions & 3 deletions R/pandoc.R
Expand Up @@ -820,6 +820,17 @@ pandoc.table.return <- function(t, caption, digits = panderOptions('digits'), de
## store missing values
wm <- which(is.na(t), arr.ind = TRUE)

## checking for empty data frames
if (length(dim(t)) > 1 && dim(t)[1] == 0) {
if (!is.null(colnames(t))) {
t <- as.data.frame(t)
t[1, ] <- NA
} else {
warning("Object is empty and without header. No output will be produced")
return(invisible())
}
}

## round numbers & cut digits & apply decimal mark & optionally remove trailing zeros
if (length(dim(t)) < 2 | !is.null(dim(t)) && length(dim(t)) == 2 && is.data.frame(t))
t.n <- as.numeric(which(sapply(t, is.numeric)))
Expand Down Expand Up @@ -894,9 +905,6 @@ pandoc.table.return <- function(t, caption, digits = panderOptions('digits'), de
}
}

## checking for empty data frames
if (length(dim(t)) > 1 && dim(t)[1] == 0)
t[1, ] <- NA

## get (col/row)names if any
t.colnames <- tryCatch(colnames(t), error = function(e) NULL)
Expand Down
23 changes: 23 additions & 0 deletions inst/tests/test-S3.R
Expand Up @@ -375,6 +375,29 @@ test_that('table.expand behaves correctly',{
expect_equal(pandoc.table.return(data.frame(a = 'ßß')), "\n---\n a \n---\nßß \n---\n\n")
})

context("Empty objects")

test_that('Behavior for empty objects is correct', {
mt <- mtcars[mtcars$mpg < 0, 1:4]
res <- pander_return(mt)
expect_equal(res[3], " mpg cyl disp hp ")
expect_equal(res[5], " NA NA NA NA ")
expect_equal(length(res), 7)
colnames(mt) <- NULL
res <- pander_return(mt)
expect_equal(length(res), 0)
expect_warning(pander_return(mt))
mt <- matrix(0, nrow = 0, ncol = 5)
res <- pander_return(mt)
expect_equal(length(res), 0)
expect_warning(pander_return(mt))
colnames(mt) <- 1:5
res <- pander_return(mt)
expect_equal(res[3], " 1 2 3 4 5 ")
expect_equal(res[5], "NA NA NA NA NA ")
expect_equal(length(res), 7)
})

context("S3 methods")

test_that('pander.tabular behaves correctly', {
Expand Down

0 comments on commit 6d324f6

Please sign in to comment.