添加将汇总子产品的新行(类别明智)

时间:2017-09-08 09:54:11

标签: r

输入数据:

Region  Country       Product   SubProduct  Period  NPE AYLR    PYD
APAC    Australia   Auto    Auto Non-PCG    2016    4   43.72%  -15.85%
APAC    Australia   Auto    Auto PCG    2016    5   0.00%    0.00%
APAC    Australia     Property   Non-PCG    2016    -0.03   127.13% -9.39%
APAC    Australia     Property   PCG            2016    19.87   72.12%   0.00%

输出:我想写下R代码,它将创建以下数据的第3行和第6行。

Region  Country       Product   SubProduct  Period  NPE AYLR    PYD
APAC    Australia   Auto    Auto Non-PCG    2016    4   43.72%  -15.85%
APAC    Australia   Auto    Auto PCG    2016    5   0.00%    0.00%
APAC    Australia   Auto    All         2016    9   21.86%  -7.92%
APAC    Australia     Property   Non-PCG    2016    -0.03   127.13% -9.39%
APAC    Australia     Property   PCG            2016    19.87   72.12%   0.00%
APAC    Australia     Property   all            2016    19.84   99.62%  -4.69%

1 个答案:

答案 0 :(得分:1)

library(data.table)
setDT(INPUT)
d <- INPUT[, .(NPE = sum(NPE), 
               AYLR = mean(as.numeric(gsub("%", "", AYLR))),
               PYD = mean(as.numeric(gsub("%", "", PYD))),
               SubProduct = "All"), 
             .(Region, Country, Product, Period)]
d <- rbind(INPUT, d)
setkey(d, Region, Country, Product, Period)


   Region   Country  Product   SubProduct Period   NPE    AYLR     PYD
1:   APAC Australia     Auto Auto_Non-PCG   2016  4.00  43.72% -15.85%
2:   APAC Australia     Auto     Auto_PCG   2016  5.00   0.00%   0.00%
3:   APAC Australia     Auto          All   2016  9.00   21.86  -7.925
4:   APAC Australia Property      Non-PCG   2016 -0.03 127.13%  -9.39%
5:   APAC Australia Property          PCG   2016 19.87  72.12%   0.00%
6:   APAC Australia Property          All   2016 19.84  99.625  -4.695