Skip to content

Instantly share code, notes, and snippets.

@ClintWeathers
Created December 10, 2015 21:35
Show Gist options
  • Save ClintWeathers/881b3bce44ad0d8f1032 to your computer and use it in GitHub Desktop.
Save ClintWeathers/881b3bce44ad0d8f1032 to your computer and use it in GitHub Desktop.
Aggregation using Dplyr
library(dplyr); library(magrittr)
#To Create The Dataframe of Fake Orders
set.seed(867.5309)
onums <- paste("AA", as.integer(runif(20) * 1e8), sep = "")
prices <- round((runif(20) * 1000), 2)
orders <- as.data.frame(cbind(onums, prices))
orders %>%
group_by(prices) %>%
summarise(orders = n())
What I get:
prices orders
(fctr) (int)
1 173.87 1
2 176.45 1
3 212.39 1
4 323.37 1
5 353.56 1
6 434.05 1
7 469.32 1
8 48.23 1
9 489.06 1
10 502.43 1
11 518.76 1
12 603.93 1
13 649.49 1
14 65.23 1
15 678.09 1
16 822.91 1
17 83.25 1
18 85.1 1
19 912.28 1
20 925.66 1
Desired Output:
0-100 4
100-200 2
200-300 1
300-400 2
400-500 3
500-600 2
600-700 3
800-900 1
900-1000 2
@marcoblume
Copy link

orders %>%
group_by(prices) %>%
summarise(orders = n()) %>%
mutate(prices = as.numeric(as.character(prices)),
container = .bincode(prices,seq(0,1000,100)) * 100
) %>%
group_by(container) %>%
summarise(Count = n())

@jkaupp
Copy link

jkaupp commented Dec 10, 2015

You can use cut as well, but you have to get the label of the factor and convert it to numeric first.

orders %>%
group_by(prices) %>%
summarise(orders = n()) %>%
mutate(cut_prices = cut(as.numeric(as.character(prices)), seq(0,1000,100), include.lowest = TRUE)) %>%
group_by(cut_prices) %>%
summarise(orders = n())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment