2

I'm trying to make a pivot table with pivottabler package. I want to convert the pivot table object to dataframe, so that I can convert it to data table (with DT) and render it in Shiny app, so that it's downloadable.

library(pivottabler)
pt = qpvt(mtcars, 'cyl', 'vs', 'n()')

I tried to convert it to matrix

as.data.frame(pt)

I got error message like below:

Error in as.data.frame.default(pt) : cannot coerce class ‘c("PivotTable", "R6")’ to a data.frame

Does anyone know how to convert the pivot table object to dataframe?

mnist
  • 6,571
  • 1
  • 18
  • 41
zesla
  • 11,155
  • 16
  • 82
  • 147
  • pivottabler has a built in function for dataframes --> `pt$asDataFrame()`. There is also a lot of framework for rendering in Shiny --> `pivottabler(pt)` see https://www.rdocumentation.org/packages/pivottabler/versions/1.2.0/vignettes/v04-outputs.Rmd – M.Viking Jun 01 '19 at 20:51
  • Thank you. For rendering in Shiny, is that easily downloadable like data table? That's the problem I have with rpivotTable package. @M. Viking – zesla Jun 01 '19 at 21:03
  • Hi @zesla, let me see if I understand; you want to render in shiny and allow the user download the pivottabler data, correct? For more on pivottabler and shiny see https://www.rdocumentation.org/packages/pivottabler/versions/1.2.0/vignettes/v11-shiny.Rmd ... and for adding a data download button to shiny see https://shiny.rstudio.com/articles/download.html and https://shiny.rstudio.com/reference/shiny/latest/downloadHandler.html – M.Viking Jun 03 '19 at 02:24

1 Answers1

3

It is an R6 class. One option would be to extract with asDataFrame which can be revealed if we check the str

str(pt)
#...
#...
#asDataFrame: function (separator = " ", stringsAsFactors = default.stringsAsFactors()) 
#asJSON: function () 
#asList: function () 
#asMatrix: function (includeHeaders = TRUE, repeatHeaders = FALSE, rawValue = FALSE) 
#asTidyDataFrame: function (includeGroupCaptions = TRUE, includeGroupValues = TRUE, 
...

Therefore, applying asDataFrame() on the R6 object

out <- pt$asDataFrame()
out
#     0  1 Total
#4      1 10    11
#6      3  4     7
#8     14 NA    14
#Total 18 14    32

str(out)
#'data.frame':  4 obs. of  3 variables:
#$ 0    : int  1 3 14 18
#$ 1    : int  10 4 NA 14
#$ Total: int  11 7 14 32

or to get a matrix, asMatrix

pt$asMatrix()
#      [,1]    [,2] [,3] [,4]   
#[1,] ""      "0"  "1"  "Total"
#[2,] "4"     "1"  "10" "11"   
#[3,] "6"     "3"  "4"  "7"    
#[4,] "8"     "14" ""   "14"   
#[5,] "Total" "18" "14" "32"   
akrun
  • 874,273
  • 37
  • 540
  • 662