I'm trying to use a function that calculates some statistics by group in a data.table
as follows:
minmax <- function(vec) {
c(min(vec), max(vec))
}
library(data.table)
iris <- as.data.table(iris)
iris[, c('Min', 'Max') := minmax(Petal.Length), by = Species]
The result should be the min and max Petal.Length
by Species
and have as many rows as there are Species. That is, the same result as the code below:
merge(
iris[, .(Min = min(Petal.Length)), Species],
iris[, .(Max = max(Petal.Length)), Species],
on = 'Species'
)
Species Min Max
1: setosa 1.0 1.9
2: versicolor 3.0 5.1
3: virginica 4.5 6.9
Note: in my own code I want to do this in one go, not using merge()
.