问题
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?
回答1:
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"
来源:https://stackoverflow.com/questions/56410154/convert-pivot-table-generated-from-pivottabler-package-to-dataframe