2017-10-09 32 views
1

我在R中有下表,它显示了原油在千桶中的进口量。列是这些年来,每年的月行:R:重组表中的行

> 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 

这是表类:

> 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 

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

这样做的最好方法是什么?

+0

是的,@www,我想要得到季度总和。 – Agarp

回答

1

可以定义间隔在一个列表中,然后lapplycolSums在其上方,每隔三行综上所述,事后rbind的这个输出与do.call(1:9,10:12 3,4:6,7) 。

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, ]))) 
0

随着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)