The analog of "ave" in plyr?

Function

R ave() more convenient than its name suggests - it is basically the tapply() version, which allows you to return a vector of the same length as the input, and discards these values ​​back in the same order as the input for you.

 > x <- 1:10 > ave(x, x %% 2, FUN=function(d) d-mean(d)) [1] -4 -4 -2 -2 0 0 2 2 4 4 

You can achieve a similar effect using ddply() , but this requires several additional copies of the data, as well as a couple of auxiliary variables:

 > x <- 1:10 > val <- ddply(data.frame(x=x, id=1:10), .(x %% 2), function(d) {d$y <- d$x-mean(d$x); d}) > val[order(val$id),]$y [1] -4 -4 -2 -2 0 0 2 2 4 4 

Is there any other plyr method that matches the lightweight approach I can get with ave() ?

+4
source share
2 answers

You can shorten the ddply code a ddply using transform :

 ddply(data.frame(x=x, id=1:10), .(x %% 2),transform,y = x - mean(x)) 

but I don’t think that the ddply and other plyr functions are really intended to replicate the ave functions that you describe. For the separation and recombination of single atomic vectors, tapply (and ave ) are probably the right tools for the job.

+8
source

I recently wrote a blog post comparing data on speed, data transfer rate, ddply and data.table. I would recommend you take a look at data.table, this might be useful. Sorry in advance if someone is offended by self-esteem.

+5
source

Source: https://habr.com/ru/post/1388172/


All Articles