将数据帧转换为“ dist”类的对象。无需实际计算R中的距离 [英] Convert a dataframe to an object of class "dist" without actually calculating distances in R

查看:132
本文介绍了将数据帧转换为“ 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))



<我需要将其转换为 dist类的对象,但不需要计算距离,因此我无法使用dist()函数。有什么建议吗?

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中的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆