convert object of class “dist” into data frame in r

前端 未结 4 1476
傲寒
傲寒 2021-02-04 14:43

if possible to convert a data frame to an object of class \"dist\" is it possible to do just the opposite? convert class \"dist\" to data frame? for example

< dist(ha

4条回答
  •  离开以前
    2021-02-04 15:04

    I would do something like this ..

    library(reshape)
    set.seed(123)
    
    mat <- matrix(rnorm(25),ncol=5,nrow=5,byrow=T) # Creating a 5 X 5 matrix
    d   <- dist(mat)
    
    df  <- melt(as.matrix(d)) #Converting the dist object to matrix while using melt
    
    p    <- t(apply(df[,c(1,2)],1,FUN=sort))
    rmv1 <- which(p[,1] == p[,2])
    
    p    <- paste(p[,1],p[,2],sep="|")
    rmv2 <- which(duplicated(p))
    
    df   <- df[-c(rmv1,rmv2),] #removing self distances and duplicated distances
    
    df
    X1 X2    value
    2  1 3.812287
    3  1 2.311832
    4  1 4.385048
    5  1 2.854179
    3  2 1.916895
    4  2 1.557744
    5  2 2.880357
    4  3 2.509214
    5  3 2.886526
    5  4 3.408147
    

提交回复
热议问题