Skip to content

Commit

Permalink
fix #1933: when col.names in kable() has more elements than the numbe…
Browse files Browse the repository at this point in the history
…r of columns when row names is treated as a column, use the last N elements (N = ncol(data)); this means the column name of row names can be specified as the first element in col.names now
  • Loading branch information
yihui committed Aug 31, 2023
1 parent 46ed210 commit 0901218
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 2 deletions.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: knitr
Type: Package
Title: A General-Purpose Package for Dynamic Report Generation in R
Version: 1.43.13
Version: 1.43.14
Authors@R: c(
person("Yihui", "Xie", role = c("aut", "cre"), email = "[email protected]", comment = c(ORCID = "0000-0003-0645-5666")),
person("Abhraneel", "Sarma", role = "ctb"),
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

- The `opts_current` object can no longer be modified within code chunks via its `$set()` method (thanks, @AshesITR, #1798).

- The argument `col.names` of `kable()` can be used to specify the column name of row names now, e.g., `kable(head(mtcars), col.names = c("car", names(mtcars)))` (`"car"` will be the column name of row names in the first column) (thanks, @iago-pssjd, #1933).

## MAJOR CHANGES

- Dashes (`-`) in the names of all chunk options are normalized to dots (`.`) now, e.g., `fig-height` will be converted to `fig.height`. This is to make **knitr** more compatible with Quarto since Quarto always use dashes in chunk option names (#2282).
Expand Down
2 changes: 1 addition & 1 deletion R/table.R
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ kable = function(
if (!is.null(align)) align = rep(align, length.out = m)
if (row.names) {
x = cbind(' ' = rownames(x), x)
if (!is.null(col.names)) col.names = c(' ', col.names)
if (!is.null(col.names)) col.names = tail(c(' ', col.names), ncol(x))
if (!is.null(align)) align = c('l', align) # left align row names
}
n = nrow(x)
Expand Down
5 changes: 5 additions & 0 deletions tests/testit/test-table.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ assert('kable() does not discard row names when there is only one row', {
(kable2(m) %==% c('| | x| y|', '|:--|--:|--:|', '|a | 1| 2|'))
})

assert('kable() can assign a column name for row names', {
(kable2(m, col.names = c('z', colnames(m))) %==%
c('|z | x| y|', '|:--|--:|--:|', '|a | 1| 2|'))
})

assert('kable() recycles the align argument correctly', {
(kable2(m, align = 'c') %==%
c('| | x | y |', '|:--|:-:|:-:|', '|a | 1 | 2 |'))
Expand Down

0 comments on commit 0901218

Please sign in to comment.