How to create a pivot table in R with multiple (3+) variables

前端 未结 5 1155
灰色年华
灰色年华 2020-12-06 07:09

I am having problems in create a pivot table with a data frame like this:

c1   c2          c3         c4
E   5.76         201    A la vista
E   47530.71              


        
5条回答
  •  有刺的猬
    2020-12-06 07:31

    This can also be easily produced by the pivottabler package - using either the one-line quick-pivot function or the more verbose syntax:

    df <- read.csv(text="c1,c2,c3,c4
        E,5.76,201,A la vista
        E,47530.71,201,A la vista
        E,82.85,201,A la vista
        L,11376.55,201,A la vista
        E,6683.37,203,A la vista
        E,66726.52,203,A la vista
        E,2.39,203,A la vista
        E,79066.07,202,Montoxv_a60d
        E,14715.71,202,Montoxv_a60d
        E,22661.78,202,Montoxv_a60d
        L,81146.25,124,Montoxv_a90d
        L,471730.2,124,Montoxv_a186d
        E,667812.84,124,Montoxv_a186d", header=TRUE)
    
    # quick pivot syntax
    library(pivottabler)
    qhpvt(df, c("c1","c3"), "c4", "sum(c2)", totals="NONE")
    
    # verbose syntax
    library(pivottabler)
    pt <- PivotTable$new()
    pt$addData(df) 
    pt$addColumnDataGroups("c4", addTotal=FALSE)
    pt$addRowDataGroups("c1", addTotal=FALSE)
    pt$addRowDataGroups("c3", addTotal=FALSE)
    pt$defineCalculation(calculationName="calc1", summariseExpression="sum(c2)")
    pt$renderPivot()
    

    Output:

    More info about the pivottabler package at: http://pivottabler.org.uk/articles/v01-introduction.html

    NB: I am the package author.

提交回复
热议问题