【发布时间】:2017-05-17 18:57:30
【问题描述】:
我在这里要做的是将 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 有更多变量时,我需要能够从函数的计算中排除分组/特定变量。
我不确定这将如何实现,但以某种方式在 .reorder_rows 函数中使用选择语义可能是解决此问题的一种方法。
【问题讨论】:
-
对于您在问题中提出的问题,就能够直接在函数中使用选择助手而言(我认为这与环境有关),肯定会更多。