我有一个包含一些信息和一些测量的数据框。对于测量,我想计算马哈拉诺比斯距离,但我没有达到干净的dplyr方法。我希望有类似的东西:
library(anomalyDetection)
test<-data.frame(id=LETTERS[1:10],
A = rnorm(10,0,2),
B = rnorm(10,5,3))
test<-test%>%
mutate(MD = mahalanobis_distance(.%>%dplyr::select(one_of(c("A","B")))))
我知道以下工作:
test<-test%>%
mutate(MD = mahalanobis_distance(test%>%dplyr::select(one_of(c("A","B")))))
但如果在mutate-call之前还有其他步骤,则会崩溃:
test<-test%>%
mutate(group = id %in% c(LETTERS[1:5]))%>%
group_by(group)%>%
mutate(MD = mahalanobis_distance(test%>%dplyr::select(one_of(c("A","B")))))
答案 0 :(得分:2)
我们可以根据逻辑向量执行split
,然后使用map_df
创建&#39; MD&#39;通过在拆分数据集
mahalanobis_distance
来创建列
library(purrr)
library(dplyr)
library(anomalyDetection)
test %>%
split(.$id %in% LETTERS[1:5]) %>%
map_df(~mutate(., MD = mahalanobis_distance(.[-1])))
# id A B MD
#1 F -0.7829759 4.22808758 2.9007659
#2 G 2.4246532 5.96043439 1.3520245
#3 H -4.8649537 4.95510794 3.0842137
#4 I 1.2221836 5.36154775 0.2921482
#5 J 0.6995204 5.63616864 0.3708477
#6 A 1.2374543 5.17288708 1.4382259
#7 B -2.7815555 0.06437452 2.1244313
#8 C -2.2160242 2.74747556 0.5088291
#9 D 0.8561507 2.70631852 1.5174367
#10 E -1.6427978 6.23758354 2.4110771
注意:在OP的帖子
中创建数据集时没有设置种子