Skip to content

Commit

Permalink
[experimental] cleanup pivot sorting (#670)
Browse files Browse the repository at this point in the history
  • Loading branch information
JanMarvin committed Jun 30, 2023
1 parent 7a37393 commit a9e5ad2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
24 changes: 17 additions & 7 deletions R/helperFunctions.R
Original file line number Diff line number Diff line change
Expand Up @@ -760,26 +760,36 @@ create_pivot_table <- function(

if (i %in% data_pos) dataField <- c(dataField = "1")

if (i %in% filter_pos) {
axis <- c(axis = "axisPage")
sort <- params$sort_page
}
if (i %in% filter_pos) axis <- c(axis = "axisPage")

if (i %in% rows_pos) {
axis <- c(axis = "axisRow")
sort <- params$sort_row

if (!is.null(sort) && !is.character(sort)) {
if (!abs(sort) %in% seq_along(rows_pos))
warning("invalid sort position found")

if (!abs(sort) == match(i, rows_pos))
sort <- NULL
}
}

if (i %in% cols_pos) {
axis <- c(axis = "axisCol")
sort <- params$sort_col

if (!is.null(sort) && !is.character(sort)) {
if (!abs(sort) %in% seq_along(cols_pos))
warning("invalid sort position found")

if (!abs(sort) == match(i, cols_pos))
sort <- NULL
}
}

if (!is.null(sort) && !is.character(sort)) {

if (abs(sort) == 0 || abs(sort) >= length(unique(x[[i]])))
warning("invalid sort position found")

autoSortScope <- read_xml(sprintf('
<autoSortScope>
<pivotArea dataOnly="0" outline="0" fieldPosition="0">
Expand Down
25 changes: 25 additions & 0 deletions tests/testthat/test-class-workbook.R
Original file line number Diff line number Diff line change
Expand Up @@ -814,4 +814,29 @@ test_that("numfmt in pivot tables works", {
"length of numfmt and data does not match"
)

### add sortType only to those pivot fields that are sorted

## sort by column and row
df <- mtcars

## Create the workbook and the pivot table
wb <- wb_workbook()$
add_worksheet("Data")$
add_data(x = df, startCol = 1, startRow = 2)

df <- wb_data(wb)
wb$add_pivot_table(
df,
dims = "A3",
rows = c("cyl", "am"),
cols = c("gear", "carb"),
data = c("disp", "mpg"),
param = list(sort_row = 1,
sort_col = -2)
)

exp <- c("", "ascending", "", "", "", "", "", "", "", "descending", "")
got <- rbindlist(xml_attr(wb$pivotTables, "pivotTableDefinition", "pivotFields", "pivotField"))$sortType
expect_equal(exp, got)

})

0 comments on commit a9e5ad2

Please sign in to comment.