How to group the results and count each group written to the matrix in R?
Here's the table:
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
I want to split all of the above content (4 columns of distance by 4 rows of the month) in 3 groups and have the counts of each group written in the matrix as such:
Month D<=700 700<D<1000 D>=1000
1. counts counts ....
2. ...
3. ....
What's the fastest way to do this?
Thank!
+3
source to share
2 answers
Solution using package data.table
:
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
Data:
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))
+2
source to share