R 在数据透视表中使用同一级别的多个字段

R 在数据透视表中使用同一级别的多个字段,r,pivot-table,R,Pivot Table,我正在pivottabler中查找为2个并行字段构建表的选项,如下所示: SEX | POPULATION GROUPS ______________________|_______________________________________ 1 | 2 | 1 | 2 | 3 | 4 ___________|_________|_________|___

我正在
pivottabler
中查找为2个并行字段构建表的选项,如下所示:

             SEX      |             POPULATION GROUPS
______________________|_______________________________________  
    1       |   2     |   1     |   2     |   3     |   4
 ___________|_________|_________|_________|_________|___________
  AgeGroups |AgeGroups|AgeGroups|AgeGroups|AgeGroups|AgeGroups            
      |  |  |   |  |  |   |  |  |   |  |  |   |  |  |   |  |     
    1 | 2| 3| 1 | 2| 3| 1 | 2| 3| 1 |2 | 3| 1 | 2| 3| 1 | 2| 3
______|__|__|___|__|__|___|__|__|___|__|__|___|__|__|___|__|___
      |  |  |   |  |  |   |  |  |   |  |  |   |  |  |   |  |           

如何添加2个或多个并行而非分层的字段?

将填充组列添加到数据透视表时,可以通过指定
atLevel=1
来完成此操作

我制作了一些示例数据,用于下面的示例中

n <- 100
sex <- sample(x=c("M","F"), size=n, replace=TRUE)
pg <- sample(x=c("pg1","pg2","pg3","pg4"), size=n, replace=TRUE)
ag <- sample(x=c("ag1","ag2","ag3"), size=n, replace=TRUE)
grp <- sample(x=c("g1","g2","g3","g4"), size=n, replace=TRUE)
df <- data.frame(sex, pg, ag, grp)

library(pivottabler)
pt <- PivotTable$new()
pt$addData(df) 
pt$addColumnDataGroups("sex", addTotal=FALSE)
pt$addColumnDataGroups("pg", atLevel=1, addTotal=FALSE)
pt$addColumnDataGroups("ag", addTotal=FALSE)
pt$addRowDataGroups("grp")
pt$defineCalculation(calculationName="Count", summariseExpression="n()")
pt$renderPivot()

n将人口组列添加到数据透视表时,可以通过指定
atLevel=1
来完成此操作

我制作了一些示例数据,用于下面的示例中

n <- 100
sex <- sample(x=c("M","F"), size=n, replace=TRUE)
pg <- sample(x=c("pg1","pg2","pg3","pg4"), size=n, replace=TRUE)
ag <- sample(x=c("ag1","ag2","ag3"), size=n, replace=TRUE)
grp <- sample(x=c("g1","g2","g3","g4"), size=n, replace=TRUE)
df <- data.frame(sex, pg, ag, grp)

library(pivottabler)
pt <- PivotTable$new()
pt$addData(df) 
pt$addColumnDataGroups("sex", addTotal=FALSE)
pt$addColumnDataGroups("pg", atLevel=1, addTotal=FALSE)
pt$addColumnDataGroups("ag", addTotal=FALSE)
pt$addRowDataGroups("grp")
pt$defineCalculation(calculationName="Count", summariseExpression="n()")
pt$renderPivot()

n请使用该表重试。使用以三个`(反勾号)开头和结尾的代码块。在那里,将使用单间距字体。另请参见:请使用表格再试一次。使用以三个`(反勾号)开头和结尾的代码块。在那里,将使用单间距字体。另见: