SriniShine
SriniShine

Reputation: 1139

R: How to convert a dataframe into a nxn matrix

I have four elements a, b, c and d. I have a function which computes the distance between these four element and write it to a file. The algorithm computes only the unique comparisons (i.e. a and b not b and a). Following is the structure of the file.

ele1 ele2 dist
a b 2.4
a c 0.5
a d 3.4
b c 0.9
b d 12.5
c d 8.3

I'm trying to write this into a nxn matrix. I used the following code.

dataFile = read.csv("distanceMeasure.csv")
dataToMatrix <- xtabs(dist ~ ele1 + ele2, data = dataFile )

However what I'm getting is;

 b c d
a
b
c

What I'm looking for is

  a b c d
a
b
c
d

Upvotes: 2

Views: 439

Answers (1)

akrun
akrun

Reputation: 887901

We can convert to factor with levels specified so as to give all the combinations even though some of the levels are missing in the column.

Un1 <-  as.character(unique(unlist(dataFile[1:2])))
dataFile[1:2] <- lapply(dataFile[1:2], factor, levels = Un1)
xtabs(dist ~ ele1 + ele2, data = dataFile)
#        ele2
#ele1    a    b    c    d
#   a  0.0  2.4  0.5  3.4
#   b  0.0  0.0  0.9 12.5
#   c  0.0  0.0  0.0  8.3
#   d  0.0  0.0  0.0  0.0

Upvotes: 1

Related Questions