如何对结果进行分组,并将每组的计数写入R中的矩阵?

如何对结果进行分组,并将每组的计数写入R中的矩阵?,r,R,这是桌子: Month D1 D2 D3 D4 1. 11149 10488 5593 3073 1. 6678 11073 789 10009 2. 2322 10899 3493 21 3. 5839 11563 4367 9987 我想将上述所有内容(4列距离除以4行月份)分成3组,并将每组的计数写入矩阵: Month D&l

这是桌子:

Month    D1       D2      D3     D4 
1.      11149   10488    5593    3073
1.      6678    11073    789     10009
2.      2322    10899    3493    21
3.      5839    11563    4367    9987
我想将上述所有内容(4列距离除以4行月份)分成3组,并将每组的计数写入矩阵:

Month        D<=700    700<D<1000   D>=1000
1.           counts       counts    ....
2.           ...          
3.           ....

D月这不是最快的方法,但您可以使用
library(重塑)
中的
melt()
cast()
:(假设
D
是您的原始
data.frame

库(重塑)

M使用
数据的解决方案。表
包:

library(data.table)
library(magrittr)

setDT(dt)[, cut(colSums(.SD),breaks=c(0,700,1000,max(colSums(.SD)))) %>%
              table %>%
              as.list
          , Month]

#   Month (0,700] (700,1e+03] (1e+03,2.16e+04]
#1:     1       0           0                4
#2:     2       1           0                3
#3:     3       0           0                4
数据:

dt = structure(list(Month = c(1, 1, 2, 3), D1 = c(11149L, 6678L, 2322L, 
5839L), D2 = c(10488L, 11073L, 10899L, 11563L), D3 = c(5593L, 
789L, 3493L, 4367L), D4 = c(3073L, 10009L, 21L, 9987L)), .Names = c("Month", 
"D1", "D2", "D3", "D4"), class = "data.frame", row.names = c(NA, 
-4L))

你能从你共享的样本数据中发布你想要的结果吗?data.table可能很快。如果你能提供一个可复制的例子,我可以告诉你怎么做。
dt = structure(list(Month = c(1, 1, 2, 3), D1 = c(11149L, 6678L, 2322L, 
5839L), D2 = c(10488L, 11073L, 10899L, 11563L), D3 = c(5593L, 
789L, 3493L, 4367L), D4 = c(3073L, 10009L, 21L, 9987L)), .Names = c("Month", 
"D1", "D2", "D3", "D4"), class = "data.frame", row.names = c(NA, 
-4L))