Elizabeth Elizabeth - 5 months ago 29
R Question

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

I have a dataframe with distances


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?


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))