问题描述
我试图更好地了解 data.table
包中的一些特殊变量是如何工作的.其中之一是 .BY
语句.我没有看到很多人使用它的例子,但文档暗示它对绘图很有用.
I am trying to get a better grasp on how some of the special variables in the data.table
package work. One of these is the .BY
statement. I have not seen a lot of examples of people using it, but the documentation implies that is is useful in plotting.
例如,以下代码在 data.table 1.9.3
中似乎运行良好(显示每个物种的图并为每个图分配正确的标题):
For example, the following code seems to work quite well (showing a plot for each of the species and assigning the right title to each plot) in data.table 1.9.3
:
iris <- data.table(iris)
iris[,plot(Sepal.Length ~ Sepal.Width, main = unlist(.BY)), by = Species]
虽然此代码无法按我的预期工作:
While this code does not work as intended by me:
iris[ , plot(Sepal.Length ~ Sepal.Width, main = .BY), by = Species]
为什么这两个不同?从评论来看,这似乎不是 data.table 1.9.2
中的问题.使用 .BY
语句还有哪些其他用途?这与 .EACHI
语句相比有何不同?
Why are these two different? From the comments, it does not seem to be an issue in data.table 1.9.2
. In what other ways might it be useful to use the .BY
statement? How is this different compared to the .EACHI
statement?
推荐答案
.BY
是一个 named list
包含 按变量.
.BY
is a named list
containing the values of the by
variables.
将未命名列表传递给 main
将起作用,但是 named 列表将失败(与 data.table
Passing an unnamed list to main
will work, however a named list will fail (wholly unrelated to data.table
plot(1, main = list(1))
# works....
plot(1, main = list(s=1))
# Error in title(...) : invalid graphics parameter
最近对 data.table 1.9.3 的提交修复了与 `.BY 中的命名有关的错误关闭错误 #5415..BY 在今年 4 月正确设置了名称属性.
There is a recent commit to data.table 1.9.3 which fixed a bug to do with naming in `.BYCloses bug #5415. .BY gets names attribute set properly in april this year.
如果您有超过 1 个by"变量,您可能希望能够连接一些方式
If you had more than 1 "by" variable, you would want to be able to concatenate some how
也许
iris[,plot(Sepal.Length~Sepal.Width,main=do.call(paste,.BY)),by=Species]
会起作用(除非您有一个名为 collapse
的列!)
will work (unless you have a column called collapse
!)
EACHI
与此完全无关.请阅读 NEWS for data.table 1.9.3 了解这一点.
EACHI
is completely unrelated to this. Please read the NEWS for data.table 1.9.3 for an understanding of this.
这篇关于在 data.table 包中使用 .BY 和 .EACHI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!