在 dplyr 管道中应用函数

Applying functions in dplyr pipes

给定一个数据框 data:

data <- data.frame(group = rep(c('a','b'), each= 100),
                   value = rnorm(200))

我们想使用 dplyr 过滤 group == b 的值,并使用 boxplot.stats 来识别异常值:

library(dplyr)
data%>%
  filter(group == 'b')%>%
  summarise(out.stats = boxplot.stats(value))

这个returns错误Column out.stats must be length 1 (a summary value), not 4,为什么这个不行?如何在管道中应用这样的函数?

问题的以下答案和问题的最后评论,其中 OP 要求异常值的行号。

what if we want to return the row numbers that go with boxplot.stats()$out from the pipe? so if we did b<-data%>%filter(group=='b') outside of the pipe, we could have used: which(b$value %in% boxplot.stats(b$value)$out)

这是通过 left_join 使用原始数据完成的。

library(dplyr)

set.seed(1234)
data <- data.frame(group = rep(c('a','b'), each= 100),
                   value = rnorm(200))

data %>% filter(group == 'b') %>% pull(value) %>% 
  boxplot.stats() %>% '[['('out') %>%
  data.frame() %>%
  left_join(data, by = c('.' = 'value'))
#          . group
#1  3.043766     b
#2 -2.732220     b
#3 -2.855759     b

我们可以使用新版本的 dplyr 也可以 return summarise 多行

library(dplyr) # >= 1.0.0
data%>%
  filter(group == 'b')%>%
  summarise(out.stats = boxplot.stats(value))
#                                              out.stats
#1 -2.4804222, -0.7546693, 0.1304050, 0.6390749, 2.2682247
#2                                                     100
#3                                 -0.08980661, 0.35061653
#4                                               -3.014914