twhitney
twhitney

Reputation: 25

How to make a matrix out of pairwise comparisons in R?

I have a very simple question but I do not know how to format the data that should be going into forming a pairwise matrix. Every type of data formation I try leads no where. I have a csv file containing a list of comparisons between individuals and want to transform it into a matrix using R. The columns are an extension of the example below.

   id1         id2        r-values

   Amy         Katie        0.5

column <-read.table("list-r-values.csv", header = TRUE, sep = ",", check.names = FALSE)


sample1<- column$id1
sample2<- column$id2
rvalues<- column$`r-values`
d <- as.data.frame(cbind(sample1, sample2, rvalues))
str(d)

b<-data.matrix(d, rownames.force = NA)

I have tried several other codes as well, I was just curious if making the csv file into a data frame is the appropriate first step?

I don't know how to get from lists and columns as the output and to make it a pairwise matrix

Upvotes: 0

Views: 2886

Answers (1)

Bill O&#39;Brien
Bill O&#39;Brien

Reputation: 872

A solution using the xtabs() function in base R.

# generate random data
set.seed(314)
df <- data.frame(id1 = sample(letters, size=5, replace=T))
df$id2 <- sample(letters, size=5, replace=T)
df$r.values <- runif(n=5)

# function to return pairwise matrix
xtabs(r.values ~ id1 + id2, data=df)

   id2
id1          b          f          l          m          v
  c 0.00000000 0.00000000 0.00000000 0.51988234 0.39122631
  g 0.00000000 0.03852331 0.00000000 0.00000000 0.00000000
  n 0.50505545 0.00000000 0.00000000 0.00000000 0.00000000
  t 0.00000000 0.00000000 0.72206577 0.00000000 0.00000000

Upvotes: 1

Related Questions