在 dplyr::mutate 函数中使用 dplyr::select 语义

Using dplyr::select semantics within a dplyr::mutate function

我在这里尝试做的是将 dplyr::select() 语义引入提供给 dplyr::mutate() 的函数中。下面是一个最小的例子。

dat <- tibble(class = rep(c("A", "B"), each = 10),
              x = sample(100, 20),
              y = sample(100, 20),
              z = sample(100, 20))

.reorder_rows <- function(...) {
    x <- list(...)
    y <- as.matrix(do.call("cbind", x))
    h <- hclust(dist(y))
    return(h$order)
}

dat %>%
    group_by(class) %>%
    mutate(h_order = .reorder_rows(x, y, z))

##    class     x     y     z h_order
##   <chr> <int> <int> <int>   <int>
## 1      A    85    17     5       1
## 2      A    67    24    35       5
## ...
## 18     B    76     7    94       9
## 19     B    65    39    85       8
## 20     B    49    11   100      10
## 
## Note: function applied across each group, A and B

我想做的是:

dat %>%
    group_by(class) %>%
    mutate(h_order = .reorder_rows(-class))

之所以重要,是因为当 dat 有更多变量时,我需要能够从函数的计算中排除 grouping/specific 变量。

我不确定这将如何实现,但在 .reorder_rows 函数中使用 select 语义可能是解决此问题的一种方法。

对于这种特殊方法,您可能应该 nestunnest(使用 tidyr)class 而不是分组它:

library(tidyr)
library(purrr)

dat %>%
  nest(-class) %>%
  mutate(h_order = map(data, .reorder_rows)) %>%
  unnest()

顺便说一句,请注意,虽然这适用于您的函数,但您也可以编写一个更短的版本来直接获取数据框:

.reorder_rows <- function(x) {
  h <- hclust(dist(as.matrix(x)))
  return(h$order)
}