“ave”的类似物在普利尔?
R 的 ave()
函数比它的名字所暗示的更有用 - 它基本上是 tapply()
的一个版本,它可以让你返回一个与输入长度相同的向量,并且将这些值重新设置为与您输入的顺序相同的顺序。
> x <- 1:10
> ave(x, x %% 2, FUN=function(d) d-mean(d))
[1] -4 -4 -2 -2 0 0 2 2 4 4
您可以使用 ddply() 实现类似的效果,但它需要几个额外的数据副本以及几个辅助变量:
> 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
是否还有其他 plyr
技术这与我可以使用 ave()
获得的轻量级方法相匹配吗?
R's ave()
function is way more useful than its name suggests - it's basically a version of tapply()
that lets you return a vector the same length as the input, and slots those values back into 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 with ddply()
, but it requires a couple extra copies of the data, as well as a couple 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 some other plyr
technique that matches the lightweight approach I can get with ave()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
transform
稍微缩短ddply
代码:但我不认为
ddply
和其他 plyr函数实际上是为了复制您描述的ave 的功能。对于拆分和重新组合单个原子向量,tapply
(和ave
)可能是适合这项工作的工具。You can shorten the
ddply
code somewhat by usingtransform
:but I don't think that
ddply
and other plyr functions are really meant to replicate the functionality ofave
that you describe. For splitting and recombining single atomic vectors,tapply
(andave
) are probably the right tools for the job.我最近写了一篇博文 比较 ave、ddply 和 data.table 的速度。我建议您查看 data.table,它可能会有所帮助。如果有人因自我推销而冒犯,请提前表示歉意。
I recently wrote a blog post comparing ave, ddply, and data.table in terms of speed. I would recommend you take a look at data.table, it might prove beneficial. Sorry in advance if anyone takes offence to the self promotion.