0

My data table looks something like this:

team player score
A     1      1
A     1      3
A     2      2
A     2      5
B     1      2
B     1      3

I want to return the rows with the min score for each team/player combo. e.g.,

A 1 1
A 2 2
B 1 2

I tried something like:

dt[, list(value=min(dt$score)), by=dt$team]

but that didn't work

Error in `[.data.frame`(dt, , list(value = min(dt$score)),  : unused argument (by = dt$team)

and it wouldn't give me what I'm looking for anyway (only team mins). Similarly, I tried:

dt[which(dt$score == min(dt$score)), ]

but that gave the min across the whole list (just A 1 1)

Any suggestions?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
mettle
  • 51
  • 4
  • 1
    `dt[dt$score==ave(dt$score, dt$team, dt$player, FUN=min), ]` if `dt` is a data.frame (as mentioned in the error message). – jogo Feb 01 '16 at 13:26
  • 2
    You haven't converted your data set to a `data.table`. First do `setDT(dt)`. Also, you probably looking for something like `setDT(dt)[, .(value = score[which.min(score)]), by = .(team, player)]` – David Arenburg Feb 01 '16 at 13:27
  • Lots of warnings and 0 row. Warnings were: 27: In FUN(X[[1100256L]], ...) : no non-missing arguments to min; returning Inf – mettle Feb 01 '16 at 13:30
  • is setDT from a specific library? – mettle Feb 01 '16 at 13:33
  • From the `data.table` package... Aren't you using this package? – David Arenburg Feb 01 '16 at 13:34
  • Here's a `dplyr` solution: `dt %>% group_by(team, player) %>% filter(score == min(score))` – ytk Feb 01 '16 at 13:37
  • My guess that `setDT(dt)[, .(value = min(score)), by = .(team, player)]` would be even better. Or `setDT(dt)[, .SD[score == min(score)], by = .(team, player)]` if you have many columns. Depends on what you need. – David Arenburg Feb 01 '16 at 13:38

1 Answers1

0

Try:

aggregate(list(score = df$score),by = list(team = df$team,player = df$player),FUN = "min")

where df is your data frame.

Data frame:

> df
  team player score
1    a      1     1
2    a      1     3
3    a      2     2
4    a      2     5
5    b      1     2
6    b      1     3

Result:

> aggregate(list(score = df$score),by = list(team = df$team,player = df$player),FUN = "min")
  team player score
1    a      1     1
2    b      1     2
3    a      2     2
R. Schifini
  • 9,085
  • 2
  • 26
  • 32