Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to sort the rows in the PivotTable #69

Open
Stanley5487 opened this issue Dec 6, 2023 · 2 comments
Open

How to sort the rows in the PivotTable #69

Stanley5487 opened this issue Dec 6, 2023 · 2 comments

Comments

@Stanley5487
Copy link

pv <- qpvt(data, rows = "party", columns = "gender", calculations = "round(mean(revenu))") pv$sortRowDataGroups(orderBy = "calculation") pv$renderPivot()

This is my code, I want to sort the data by the total "calculation"(revenue mean)belonging to the "male" in the columns "gender"; however, it just can sort by the total "calculation"(revenue mean). How can I fix it?

@Stanley5487 Stanley5487 changed the title How to sort the row data in the PivotTable How to sort the rows in the PivotTable Dec 6, 2023
@cbailiss
Copy link
Owner

cbailiss commented Dec 6, 2023

This is more involved and can't be done with the quick pivot functions (e.g. qpvt).
To sort just by male, you need to define an additional (hidden) calculation that always returns the values for male, then use this calculation to sort on. The new calculation is specified with a filter override that always returns calculates the value for male.

Example code - sorting by the male value in descending order (highest first):

party = c(1, 2, 1, 2, 1)
gender = c("M", "M", "F", "F", "F")
revenu = c(25, 20, 5, 20, 10)
data = data.frame(party=party, gender=gender, revenu=revenu)

library(pivottabler)
pv <- PivotTable$new()
pv$addData(data)
pv$addColumnDataGroups("gender")
pv$addRowDataGroups("party")
pv$defineCalculation(calculationName="MeanRevenu", summariseExpression="round(mean(revenu))")
onlyMaleFilter <- PivotFilterOverrides$new(pv, variableName="gender", values="M", action="replace")
pv$defineCalculation(calculationName="CustomSort",
                     filters=onlyMaleFilter,
                     summariseExpression="round(mean(revenu))", visible=TRUE)
pv$evaluatePivot()
pv$sortRowDataGroups(calculationName = "CustomSort", sortOrder = "desc")
pv$renderPivot()

This generates the following:

image

The values in the "CustomSort" columns always show the calculation value for male, even under the "F" and "Total" column headings.

The custom calculation can then be hidden by changing the visible=TRUE to visible=FALSE in the code above:

image

@Stanley5487
Copy link
Author

Thank you!! I will try it tomorrow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants