我在这里试图做的是将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函数中使用select语义可能是解决这个问题的一种方法。
发布于 2017-05-17 19:09:34
对于这种特定的方法,您可能应该按类嵌套和取消嵌套(使用tidyr),而不是按类分组:
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)
}https://stackoverflow.com/questions/44032818
复制相似问题