diff --git a/R/helperFunctions.R b/R/helperFunctions.R index 4b338b4ec..733a514f3 100644 --- a/R/helperFunctions.R +++ b/R/helperFunctions.R @@ -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(' diff --git a/tests/testthat/test-class-workbook.R b/tests/testthat/test-class-workbook.R index 0df79bc87..251a148bb 100644 --- a/tests/testthat/test-class-workbook.R +++ b/tests/testthat/test-class-workbook.R @@ -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) + })