用R编程语言创建OLAP多维数据集

时间:2017-08-17 10:21:41

标签: r olap data-manipulation rpivottable

您好我有以下数据

  Function    SB `Country Region` `+1 Function` `+1 SB` `+1 Country Region`
     <chr> <chr>            <chr>         <chr>   <chr>               <chr>
1      ENG  SB10             AMER           ENG    SB10                AMER
2       IT  SB07             EMEA            IT    SB07                EMEA
3      QLT  SB05             EMEA           QLT    SB05                EMEA
4      MFG  SB07             EMEA           MFG    SB07                EMEA
5      MFG  SB04             EMEA           MFG    SB05                EMEA
6      SCM  SB08             EMEA           SCM    SB08                EMEA

我想创建三维OLAP多维数据集,其中列功能SB国家/地区应该在行中,+1 Function+1 SB+1 Country Region应该在列中。

输出应采用以下格式

                   `+1 Function` `+1 SB` `+1 Country Region`  
Function
SB 
Country Region

谢谢

添加精确的RpivotTable输出。

enter image description here

1 个答案:

答案 0 :(得分:1)

例如,您可以使用WITH StudentCte As ( SELECT FirstName, ROW_NUMBER() OVER(Partition by FirstName ORDER BY (SELECT NULL)) as RowNum FROM Student ) DELETE FROM StudentCte WHERE RowNum > 1; SELECT * From Student;

ftable()

df <- read.table(text = " Function SB 'Country Region' '+1 Function' '+1 SB' '+1 Country Region' ENG SB10 AMER ENG SB10 AMER IT SB07 EMEA IT SB07 EMEA QLT SB05 EMEA QLT SB05 EMEA MFG SB07 EMEA MFG SB07 EMEA MFG SB04 EMEA MFG SB05 EMEA SCM SB08 EMEA SCM SB08 EMEA", stringsAsFactors = FALSE, header = TRUE, check.names = FALSE) foo <- ftable(df, row.vars = c(3, 1, 2), col.vars = c(6, 4, 5)) as.matrix(foo)[apply(foo, 1, function(x) any(x != 0)), apply(foo, 2, function(x) any(x != 0))] # Or simply: as.matrix(foo)[apply(foo, 1, any), apply(foo, 2, any)] # +1 Country Region_+1 Function_+1 SB # Country Region_Function_SB AMER_ENG_SB10 EMEA_IT_SB07 EMEA_MFG_SB05 EMEA_MFG_SB07 EMEA_QLT_SB05 EMEA_SCM_SB08 # AMER_ENG_SB10 1 0 0 0 0 0 # EMEA_IT_SB07 0 1 0 0 0 0 # EMEA_MFG_SB04 0 0 1 0 0 0 # EMEA_MFG_SB07 0 0 0 1 0 0 # EMEA_QLT_SB05 0 0 0 0 1 0 # EMEA_SCM_SB08 0 0 0 0 0 1 的比较:

enter image description here