[datatable-help] data.table question: ave like behavior

Short, Tom TShort at epri.com
Mon May 24 16:38:14 CEST 2010


> From: datatable-help-bounces at lists.r-forge.r-project.org
[mailto:datatable-help-bounces at lists.r-forge.r-project.org] On Behalf Of
Ozan Bakis
> Sent: Monday, May 24, 2010 10:12
> To: datatable-help at lists.r-forge.r-project.org
> Subject: [datatable-help] data.table question: ave like behavior
>  
>  
> Hi,
>  
> I have just noticed and installed your package and am trying to
understand how it works.
> The commented part in the following example from the reference manual
(p. 20) gives an error. 
>  
> dt <- data.table(a=rep(1:5, 1), b=1:10)
> transform(dt, c = a^2)
> within(dt, {
> b <- rev(b)
> c <- a^2
> rm(a)
> })
> dt[, transform, c = max(b), by="a"] # like "ave
>  

Ozan, we experimented with that syntax for a while, but it was
slow, so we took it out. The new syntax is as follows:

dt[, transform(.SD, c = max(b)), by = a]

.SD is a datatable of the subset, so you can manipulate that, in
this case with transform.

Another way to get ave functionality is:

dt$c <- dt[, rep(max(b), length(a)), by = a]$V1

This may be a little faster and more memory friendly (and maybe
harder to read).

You should be able to adapt either approach to the second part of 
your email.

- Tom


More information about the datatable-help mailing list