R:在 table 中重新组合行

R: Regrouping rows in a table

我在 R 中有以下 table。它以千桶为单位显示原油进口。列是年份,行是每年的月份:

> oil
     Year
Month   2014   2015   2016   2017
   1  288458 293297 300915 331240
   2  256340 259626 291915 281094
   3  286934 298196 310038 311840
   4  288002 281216 294659 307314
   5  291004 294570 315600 329468
   6  265109 288139 301625 307190
   7  294363 296712 326494 305336
   8  288878 305609 319990      0
   9  275435 280736 305981      0
   10 276658 274087 300671      0
   11 270260 274532 308776      0
   12 291463 302014 303563      0

这是 tables class:

> class(oil)
[1] "xtabs" "table"

我想将其重新分组为季度而不是月份:

Quarter   2014   2015   2016   2017
       1  288458 293297 300915 331240
       2  256340 259626 291915 281094
       3  286934 298196 310038 311840
       4  288002 281216 294659 307314

请注意,这不是实际的季度数字,我只是用它们来说明。

最好的方法是什么?

您可以在列表中定义间隔 (1:3, 4:6, 7:9, 10:12),然后 lapply colSums 覆盖它每三行求和,然后 rbinddo.call.

输出
data(iris)

mytable <- with(iris, table(Sepal.Length, Species))
mytable <- mytable[1:12,]


> mytable
            Species
Sepal.Length setosa versicolor virginica
         4.3      1          0         0
         4.4      3          0         0
         4.5      1          0         0
         4.6      4          0         0
         4.7      2          0         0
         4.8      5          0         0
         4.9      4          1         1
         5        8          2         0
         5.1      8          1         0
         5.2      3          1         0
         5.3      1          0         0
         5.4      5          1         0

mylist <- list(1:3, 4:6, 7:9, 10:12)

quartertable <- do.call(rbind, lapply(mylist, function(x) colSums(mytable[x,])))

> quartertable
     setosa versicolor virginica
[1,]      5          0         0
[2,]     11          0         0
[3,]     20          4         1
[4,]      9          2         0

对于您的示例,这将是:

mylist <- list(1:3, 4:6, 7:9, 10:12)

oil_quarters <- do.call(rbind, lapply(mylist, function(x) colSums(oil[x, ])))

使用 dplyr,如果您的数据在 data.frame 中,您可以

oil %>% 
  group_by(quarter = ceiling(Month/3)) %>% 
  select(-Month) %>% 
  summarise_each(funs(sum))

这适用于石油

oil <- fread('Month   2014   2015   2016   2017
   1  288458 293297 300915 331240
   2  256340 259626 291915 281094
   3  286934 298196 310038 311840
   4  288002 281216 294659 307314
   5  291004 294570 315600 329468
   6  265109 288139 301625 307190
   7  294363 296712 326494 305336
   8  288878 305609 319990      0
   9  275435 280736 305981      0
   10 276658 274087 300671      0
   11 270260 274532 308776      0
   12 291463 302014 303563      0', header = T)