1

I want to add two columns to the mtcars dataset and keeping all the data If I add one column, it's work :

dt <- as.data.table(mtcars)

dt[, max_mpg := max(mpg), by = cyl][]

But when I add the second columns I have an error :

dt[, list(max_mpg := max(mpg), min_mpg := min(mpg)), by = cyl][]

I want to keep all others column, something similar to the mutate function in dplyr

Thanks

Mostafa90
  • 1,674
  • 1
  • 21
  • 39

3 Answers3

4

Better yet, you can follow conventional data.table syntax and use

DT[, ":="(max_mpg = max(mpg), min_mpg = min(mpg)), by = cyl]
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
JPM
  • 144
  • 9
3

You can do it using:

dt[, max_mpg := max(mpg), by = cyl][, min_mpg := min(mpg), by = cyl]
head(dt)

#    mpg cyl disp  hp drat    wt  qsec vs am gear carb max_mpg min_mpg
#1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4    21.4    17.8
#2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4    21.4    17.8
#3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    33.9    21.4
#4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1    21.4    17.8
#5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2    19.2    10.4
#6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1    21.4    17.8
sm925
  • 2,648
  • 1
  • 16
  • 28
2

Maybe this is a duplicate of Assign multiple columns using := in data.table, by group

But use

dt[ , c("max_mpg", "min_mpg") := list(max(mpg), min(mpg)), by = cyl][]
Bruno
  • 4,109
  • 1
  • 9
  • 27