For the iris
data set, I am trying to find the Mahalanobis distances between each pair of species. I have tried the following but have had no luck. I tried the following:
group <- matrix(iris$Species)
group <- t(group[,-5])
variables <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
varibles <- as.matrix(iris[,variables])
mahala_sq <- pairwise.mahalanobis(x=variables, grouping=group)
But get the error message
Error in pairwise.mahalanobis(x = variables, grouping = group) : nrow(x) and length(grouping) are different
This works:
x
should be a numeric matrix of observations (columns=variables, rows=observations)grouping
should be a "vector of characters or values designating group classification for observations" with length equal tonrow(x)
I realized in editing your question that the problem stems from a typo (you assigned
varibles
instead ofvariables
); if you fix that typo, your code seems to work (at least doesn't throw an error). (I still claim that my solution is simpler ...)if you wanted to be a little more careful you could use
x <- iris[colnames(x) != "Species"]
(or asubset(select=)
ordplyr::select()
analog) to refer to the omitted column by name rather than position.If you want (for some reason) to run this analysis with a single response variable, you need to use
drop=FALSE
to prevent a one-column matrix from being collapsed to a vector, i.e. usex=iris[,1,drop=FALSE]