Last active
June 19, 2017 22:18
-
-
Save ZeccaLehn/e950eab0c07a2891e912f9a50d01f055 to your computer and use it in GitHub Desktop.
Aggregate versus merge MTCARS with R data.table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
###### 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