是否可以重用 ddply 中生成的列?
我有一个使用 ddply 的脚本,如下例所示:
ddply(df, .(col),
function(x) data.frame(
col1=some_function(x$y),
col2=some_other_function(x$y)
)
)
在 ddply 中,是否可以重用 col1 而无需再次调用整个函数?
例如:
ddply(df, .(col),
function(x) data.frame(
col1=some_function(x$y),
col2=some_other_function(x$y)
col3=col1*col2
)
)
I have a script where I'm using ddply, as in the following example:
ddply(df, .(col),
function(x) data.frame(
col1=some_function(x$y),
col2=some_other_function(x$y)
)
)
Within ddply, is it possible to reuse col1 without calling the entire function again?
For example:
ddply(df, .(col),
function(x) data.frame(
col1=some_function(x$y),
col2=some_other_function(x$y)
col3=col1*col2
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您有一个完整的函数可以使用!不一定是单行本!这应该有效:
You've got a whole function to play with! Doesn't have to be a one-liner! This should work:
这似乎是使用
j
组件的作用域规则的data.table
的良好候选者。有关详细信息,请参阅常见问题解答 2.8。来自常见问题解答
因此,对于您的情况
或更直接的方式:
这避免了
col1
和col2
各重复一次,并避免col3
重复两次;我们努力在data.table
中减少重复。=
后面跟着<-
最初可能看起来很麻烦。不过,这允许使用以下语法糖:例如,输出可以直接发送到 Latex 或 html。
This appears to be a good candidate for
data.table
using the scoping rules of thej
component. See FAQ 2.8 for details.From the FAQ
So, for your case
or a slightly more direct way :
This avoids one repetition each of
col1
andcol2
, and avoids two repeats ofcol3
; repetition is something we strive to reduce indata.table
. The=
followed by<-
might initially look cumbersome. That allows the following syntactic sugar, though :where the output can be sent directly to latex or html, for example.
我认为这是不可能的,但它应该不会太重要,因为那时它不再是一个聚合函数。例如:
所以我没有直接计算 SE,但在
ddply()
之外计算它也不错。如果你真的愿意,你也可以做或者用你的例子来表达
I don't think that's possible, but it shouldn't matter too much, because at that point it's not an aggregation function anymore. For example:
So I didn't calculate the SEs directly, but it wasn't so bad calculating it outside of
ddply()
. If you really wanted to, you could also doOr to put it in terms of your example