Elizabeth Elizabeth - 1 year ago 69
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?

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download