运行 一个 assert() 检查在线数据的一个子集而不修改输出 data.frame

Run an assert() check on a subset of the data in-line without modifying output data.frame

我想用 assertr::assert() 免除几行检查,而不修改通过的 data.frame。

例如,假设我想断言 mtcars$qsec 没有重复值,其中 mtcars$am0。我想免除 am = 1 的值并取回所有 mtcars.

这应该失败了:

library(assertr)
mtcars %>%
  assert(is_uniq, qsec)

这有效,但通过过滤 data.frame:

mtcars %>% 
  filter(am == 0) %>% 
  assert(is_uniq, qsec)

我想要的是这个,如果 am == 0 的 qsec 没有重复值,它将成功并传递所有数据,如果有,则抛出错误:

mtcars %>% 
  assert(filter(., am == 0), is_uniq, qsec)

但这不起作用。有没有一种方法可以检查管道中的数据子集,同时仍然在最后设置整个数据?

您可以使用 lambda 表达式,如 ?magrittr::`%>%` 中所述:

mtcars0 <- mtcars %>% { {assert(filter(., am == 1), is_uniq, qsec); .} }
identical(mtcars0, mtcars)
## [1] TRUE

也许更通俗易懂的例子:

d <- data.frame(g = rep(1:2, each = 3), x = c(1, 2, 3, rep(4, 3)))
##   g x
## 1 1 1
## 2 1 2
## 3 1 3
## 4 2 4
## 5 2 4
## 6 2 4

d0 <- d %>% { {assert(filter(., g == 1), is_uniq, x); .} }
identical(d0, d)
## [1] TRUE

d %>% { {assert(filter(., g == 2), is_uniq, x); .} }
## Column 'x' violates assertion 'is_uniq' 3 times
##     verb redux_fn predicate column index value
## 1 assert       NA   is_uniq      x     1     4
## 2 assert       NA   is_uniq      x     2     4
## 3 assert       NA   is_uniq      x     3     4
##
## Error: assertr stopped execution