我在這裏要做的是將dplyr :: select()語義引入提供給dplyr :: mutate()的函數。下面是一個簡單的例子。在dplyr :: mutate函數中使用dplyr :: select語義
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語義可能是解決此問題的一種方法。
絕對是更多的爲你問你的問題,在能夠使用選擇傭工di直接在一個函數內(我認爲它與環境有關)。 –