“ave”的类似物在普利尔?

发布于 2024-12-22 23:15:42 字数 592 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小伙你站住 2024-12-29 23:15:42

您可以使用 transform 稍微缩短 ddply 代码:

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

但我不认为 ddply 和其他 plyr函数实际上是为了复制您描述的ave 的功能。对于拆分和重新组合单个原子向量,tapply(和ave)可能是适合这项工作的工具。

You can shorten the ddply code somewhat by using transform:

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

but I don't think that ddply and other plyr functions are really meant to replicate the functionality of ave that you describe. For splitting and recombining single atomic vectors, tapply (and ave) are probably the right tools for the job.

贱人配狗天长地久 2024-12-29 23:15:42

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文