Skip to content

Instantly share code, notes, and snippets.

@indapa
Last active December 11, 2015 03:09
Show Gist options
  • Save indapa/4536109 to your computer and use it in GitHub Desktop.
Save indapa/4536109 to your computer and use it in GitHub Desktop.
aggregate function in R Splits the data into subsets, computes summary statistics for each, and returns the result in a convenient form.
# how to use aggregate function in R
#say I have a data frame where I keep track how much gas I paid for each time to the pump
read.csv("gas.csv",header=T)
head(gas)
# amount month
#1 36.21 Jun
#2 30.22 Jun
#3 35.42 Jul
#4 34.12 Jul
#5 36.09 Aug
#6 35.29 Sept
#we can aggregate numbers for each month
#each call to aggregate returns a dataframe
#total amount for each month
aggregate(gas["amount"], by=gas[c("month")],FUN=sum)
# month amount
#1 Aug 36.09000
#2 Dec 32.14667
#3 Jul 34.77000
#4 Jun 33.21500
#5 Nov 28.57667
#6 Oct 35.20000
#7 Sept 35.27000
#average amount paid each trip in each month
aggregate(gas["amount"], by=gas[c("month")],FUN=mean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment