dist(www, diag = TRUE, upper = TRUE)
n <- -dist(www, diag = TRUE, upper = FALSE )
With dist(), I could make only half of the table right. (All negative or all positive)
how do I make a distance matrix according to the distances given, in a way that it shows negative and positive values like in the image?
is there a way I could make such a table instead of just importing a dataset?
CodePudding user response:
You may multiply the lower triangle of the matrix by -1.
df <- head(mtcars)
mat <- as.matrix(dist(df, upper = TRUE))
mat[lower.tri(mat)] <- mat[lower.tri(mat)] * -1
mat
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout Valiant
#Mazda RX4 0.00000 0.61533 54.909 98.113 210.34 65.472
#Mazda RX4 Wag -0.61533 0.00000 54.892 98.096 210.34 65.439
#Datsun 710 -54.90861 -54.89152 0.000 150.994 265.08 117.755
#Hornet 4 Drive -98.11252 -98.09589 -150.994 0.000 121.03 33.551
#Hornet Sportabout -210.33744 -210.33585 -265.083 -121.030 0.00 152.124
#Valiant -65.47177 -65.43922 -117.755 -33.551 -152.12 0.000