Reputation: 514
I have a dataframe with some info and some measurement. For the measurement, I want to calculate the mahalanobis distance, but I don't get to a clean dplyr-approach. I would like to have something like:
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")))))
I know that the following works:
test<-test%>%
mutate(MD = mahalanobis_distance(test%>%dplyr::select(one_of(c("A","B")))))
but that breaks down if there are some other step preceding the 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")))))
Upvotes: 3
Views: 378
Reputation: 887108
We can do a split
based on the logical vector, then with map_df
create the 'MD' column by applying the mahalanobis_distance
on the split dataset
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
NOTE: There was no seed set while creating the dataset in the OP's post
Upvotes: 2