简体   繁体   English

为什么两个 ggplot 对象通过 all.equal() 测试,但没有通过 same() 测试?

[英]Why do two ggplot objects pass an all.equal() test, but fail identical() test?

I want to test if two graphs generated by ggplot are the same.我想测试 ggplot 生成的两个图形是否相同。 One option would be to use all.equal on the plot objects, but I'd rather have a harder test to ensure they're the same, which seems like is something identical() provides me.一种选择是在绘图对象上使用all.equal ,但我宁愿进行更难的测试以确保它们相同,这似乎是identical()为我提供的。

However, when I tested two plot objects created with the same data and the same aes , I've found that all.equal() recognizes them as being the same, whereas the objects didn't pass the identical test.但是,当我测试使用相同data相同aes创建的两个绘图对象时,我发现all.equal()将它们识别为相同,而对象没有通过identical测试。 I'm not sure why and I'd love to learn more.我不知道为什么,我很想了解更多。

Basic example:基本示例:

graph <- ggplot2::ggplot(data = iris, aes(x = Species, y = Sepal.Length))
graph2 <- ggplot2::ggplot(data = iris, aes(x = Species, y = Sepal.Length))

all.equal(graph, graph2)
# [1] TRUE

identical(graph, graph2)
# [1] FALSE

The graph and graph2 objects contain environments and each time an environment is generated it is different even if it holds the same values. graphgraph2对象包含环境,并且每次生成环境时,即使它具有相同的值,它也是不同的。 R lists are identical if they have the same contents.如果 R 列表具有相同的内容,则它们是相同的。 This can be stated by saying that environments have object identity apart from their values whereas the values of the list form the identity of the list.这可以说环境除了它们的值之外还具有对象标识,而列表的值形成了列表的标识。 Try:尝试:

dput(graph)

giving the following which includes environments denoted by <environment> in the dput output: (continued after output)给出以下内容,其中包括dput输出中由<environment>表示的<environment> dput输出后继续)

...snip...
), class = "factor")), .Names = c("Sepal.Length", "Sepal.Width", 
"Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 
-150L), class = "data.frame"), layers = list(), scales = <environment>, 
    mapping = structure(list(x = Species, y = Sepal.Length), .Names = c("x", 
    "y"), class = "uneval"), theme = list(), coordinates = <environment>, 
    facet = <environment>, plot_env = <environment>, labels = structure(list(
        x = "Species", y = "Sepal.Length"), .Names = c("x", "y"
    ))), .Names = c("data", "layers", "scales", "mapping", "theme", 
"coordinates", "facet", "plot_env", "labels"), class = c("gg", 
"ggplot"))

For example, consider:例如,考虑:

g <- new.env()
g$a <- 1

g2 <- new.env()
g2$a <- 1

identical(as.list(g), as.list(g2))
## [1] TRUE

all.equal(g, g2) # the values are the same
## [1] TRUE

identical(g, g2) # but they are not identical
## [1] FALSE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM