Elizabeth Elizabeth - 1 month ago 5
R Question

Convert a dataframe to an object of class "dist" without actually calculating distances in R

I have a dataframe with distances

df<-data.frame(site.x=c("A","A","A","B","B","C"),
site.y=c("B","C","D","C","D","D"),Distance=c(67,57,64,60,67,60))


I need to convert this to an object of class "dist" but I do not need to calculate a distance so therefore I cannon use the dist() function. Any advice?

Answer

I had a similar problem not to long ago and solved it like this:

n <- max(table(df$site.x)) + 1  # +1,  so we have diagonal of 
res <- lapply(with(df, split(Distance, df$site.x)), function(x) c(rep(NA, n - length(x)), x))
res <- do.call("rbind", res)
res <- rbind(res, rep(NA, n))
res <- as.dist(t(res))
Comments