本文介绍了将数据帧转换为“ dist”类的对象。无需实际计算R中的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个距离数据框

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?

推荐答案

不久前我遇到了类似的问题,并像这样解决了它:

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

这篇关于将数据帧转换为“ dist”类的对象。无需实际计算R中的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:54
查看更多