1

我目前正在编写漩涡课程,我试图测试用户创建的 ggplot2 对象是否与all.equal()我在自定义 AnswerTest 中创建的对象有点相等()。但是,我通过访问 e$val 从 swirl api 接收的绘图对象通常继承了一个 flipped_aes = FALSE 属性,我无法在自己的绘图中创建该属性,因此all.equal(e$val, someplot)尽管它们看起来相等,但仍会失败。

我真的很感激一些想法如何解决它或控制它的发生!

如果发生 all.equal() 失败并显示以下消息:

"Component “layers”: Component 1: Component 4: Length mismatch: comparison on first 2 components"

我当前的测试如下所示:

calculates_same_graph <- function(expression){ #If ggplot expression must be written in curly brackets in Yaml file
   e <- get("e", parent.frame())
   eSnap <- cleanEnv(e$snapshot)
   
   val <- expression
   
   passed <- isTRUE(all.equal(val[-8], e$val[-8]))
   assign("e", e$val, envir = globalenv()) #only for diagnostics, changes 
                                           #when new answer is put in
   return(passed)
}
4

1 回答 1

1

好的,我同意这有点奇怪,但我发现该flipped_aes参数仅在打印绘图后才存在。奇怪的是,这似乎是打印情节的对象修改副作用。这仅在参数以某种方式被缓存时才有意义。

假设我们有两个具有相反审美翻转的地块:

library(ggplot2)

# Should have flipped_aes = FALSE
plot1 <- ggplot(iris, aes(Species, Sepal.Width)) +
  geom_col()

# Should have flipped_aes = TRUE
plot2 <- ggplot(iris, aes(Sepal.Width, Species)) +
  geom_col()

我们可以看到这些未打印的对象flipped.aes在其几何参数中没有。

# Before printing plot
plot1$layers[[1]]$geom_params
#> $width
#> NULL
#> 
#> $na.rm
#> [1] FALSE

plot2$layers[[1]]$geom_params
#> $width
#> NULL
#> 
#> $na.rm
#> [1] FALSE

现在我们可以将这些图打印到一个临时文件中。只是在控制台中打印它也应该可以工作,我只是无法在 reprex 中复制它。

# Printing as tempfile
tmp <- tempfile(fileext = ".png")
png(tmp)
plot1
plot2
dev.off()
#> png 
#>   2
unlink(tmp)

现在,在我们打印完绘图之后,绘图对象突然有了flipped_aes参数。

# After printing plot
plot1$layers[[1]]$geom_params
#> $width
#> NULL
#> 
#> $na.rm
#> [1] FALSE
#> 
#> $flipped_aes
#> [1] FALSE

plot2$layers[[1]]$geom_params
#> $width
#> NULL
#> 
#> $na.rm
#> [1] FALSE
#> 
#> $flipped_aes
#> [1] TRUE

reprex 包创建于 2021-03-10 (v1.0.0)

我不知道在你的漩涡测试中处理这种奇怪的最好方法是什么,但似乎情节的打印会影响该参数。

于 2021-03-10T17:09:34.387 回答