Skip to content

Instantly share code, notes, and snippets.

@ZeccaLehn
Last active June 19, 2017 22:18
Show Gist options
  • Save ZeccaLehn/e950eab0c07a2891e912f9a50d01f055 to your computer and use it in GitHub Desktop.
Save ZeccaLehn/e950eab0c07a2891e912f9a50d01f055 to your computer and use it in GitHub Desktop.
Aggregate versus merge MTCARS with R data.table
###### MTCARS Merging and Aggregation Example ######
### Prepare data and load library
library(data.table)
mtcarsDt <- as.data.table(mtcars); mtcarsDt
mtcarsDt <- cbind(carBrand = rownames(mtcars), mtcarsDt); mtcarsDt
## Use list to aggregate
aggregateMtCars <- mtcarsDt[, list(nAgg = .N, meanHPagg = mean(hp)), by = c("gear", "am")]
aggregateMtCars
# Use multiple lines without merge to prove above aggregation
mtcarsDt[, n := .N, by=c("gear", "am")]
mtcarsDt[, meanHP := mean(hp), by=c("gear", "am")]
mtcarsDt
#### To prove list method above
mtcarsDt <- merge(mtcarsDt, aggregateMtCars, by = c("gear","am")); mtcarsDt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment