gpt4 book ai didi

R - 在 dplyr 中使用 group_by() 和 mutate() 来应用返回组长度向量的函数

转载 作者:行者123 更新时间:2023-12-03 23:14:29 27 4
gpt4 key购买 nike

以以下示例数据为例:

set.seed(1)

foo <- data.frame(x=rnorm(10, 0, 10), y=rnorm(10, 0, 10), fac = c(rep("A", 5), rep("B", 5)))

我想通过变量“fac”将数据帧“foo”拆分为 A 和 B,应用返回每个子组长度向量的函数(马氏距离),然后将输出变异回原始数据帧。例如:
auto.mahalanobis <- function(x) {
temp <- x[, c("x", "y")]
return(mahalanobis(temp, center = colMeans(temp, na.rm=T), cov = cov(temp,
use="pairwise.complete.obs")))
}

foo %>% group_by(fac) %>%
mutate(mahal = auto.mahalanobis(.))

这给出了一个错误。显然,可以通过拆分数据集、应用函数并将输出添加为一列,然后再将其全部重新组合在一起来手动完成此过程。但是必须有一种更有效的方法来做到这一点(也许这是对 dplyr 的滥用?)。

最佳答案

你可以简单地做 -

foo %>% group_by(fac) %>%
mutate(mahal = auto.mahalanobis(data.frame(x, y)))

# A tibble: 10 x 4
# Groups: fac [2]
x y fac mahal
<dbl> <dbl> <fct> <dbl>
1 - 6.26 15.1 A 1.02
2 1.84 3.90 A 0.120
3 - 8.36 - 6.21 A 2.81
4 16.0 -22.1 A 2.84
5 3.30 11.2 A 1.21
6 - 8.20 - 0.449 B 2.15
7 4.87 - 0.162 B 2.86
8 7.38 9.44 B 1.23
9 5.76 8.21 B 0.675
10 - 3.05 5.94 B 1.08

您可以删除 temp <- x[, c("x", "y")]从您的函数中,只需使用 temp而不是 x作为函数参数。

清理功能——
auto.mahalanobis <- function(temp) {
mahalanobis(temp,
center = colMeans(temp, na.rm=T),
cov = cov(temp, use="pairwise.complete.obs")
)
}

顺便说一句,你的第一篇文章干得好!

关于R - 在 dplyr 中使用 group_by() 和 mutate() 来应用返回组长度向量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53660849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com