将从数据透视表包生成的数据透视表转换为数据框 [英] Convert pivot table generated from pivottabler package to dataframe

查看:80
本文介绍了将从数据透视表包生成的数据透视表转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pivottabler软件包制作数据透视表.我想将数据透视表对象转换为数据框,以便可以将其转换为数据表(使用DT)并在Shiny应用程序中呈现,以便可以下载.

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()')

我试图将其转换为矩阵

as.data.frame(pt)

我收到如下错误消息:

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?

推荐答案

这是一个R6类.一种选择是用asDataFrame提取,如果我们检查str

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, 
...

因此,在R6对象上应用asDataFrame()

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

或获取matrixasMatrix

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"   

这篇关于将从数据透视表包生成的数据透视表转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆