1

I am using the Theoph dataset from the datasets package in R, as an exercise. I wanted to see if I could get the Time at which each subject achieved their maximal concentration. How can I do this using data.table?

Edit: This is what I tried before, and didn't work:

library(data.table)
theophylline <- as.data.table(Theoph)
theophylline[,.(Time), by = .(by1 = Subject, by2 = conc)]

But got the answer I wanted with @Akrun's code:

theophylline[, Time[which.max(conc)],Subject]
Frank
  • 66,179
  • 8
  • 96
  • 180
KVemuri
  • 194
  • 1
  • 16
  • Please [edit your question as shown here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) ie add sample code, current and expected output. – NelsonGon Jun 13 '19 at 14:46
  • The linked question is somewhat more general (about selecting an entire row), but you can choose columns at the end like `theophylline[ theophylline[, .I[which.max(conc)], Subject]$V1, .(Subject, Time) ]` or `theophylline[, .SD[which.max(Time)], by=Subject, .SDcols="Time" ]` – Frank Jun 13 '19 at 14:56
  • @Frank, Thanks for your response. The first bit of code in your response gave me the same results as @Akrun's code, which I felt was also much simpler (also why I accepted his answer). Your second answer gave me the peak time for each subject, not the time at the peak concentration. `.SD[which.max(Time)]` in your code should probably read `.SD[which.max(conc)]` ? – KVemuri Jun 13 '19 at 17:03
  • Yeah, sorry; you are right. That was my typo / brain-fart – Frank Jun 13 '19 at 17:04

1 Answers1

2

With dat.atable, we group by 'Subject', use which.max to get the index where 'conc' is maximum, and with that index, subset the 'Time'

library(data.table)
setDT(Theoph)[, .(TimeMaxConc = Time[which.max(conc)]), by = Subject]
akrun
  • 874,273
  • 37
  • 540
  • 662