1

I have a vector in R, say c(2, 2, 3, 2, 3, 4, 4), and I want to build a square matrix of size n (the number of elements of the vector) that has a 1 if the element i of the vector has the same value of the element j , and 0 otherwise. In this example , the element [1,2] and [1,4] of the matrix must have a 1 because the first, second and fourth elements of the vector are the same. Is there a way to do this ? A command or function to build ? Something with combinations ? I would like to avoid loops like for.

Thank you !

coolsv
  • 781
  • 5
  • 16

2 Answers2

4

This just came to my mind... Is this what you want?

a <- c(2, 2, 3, 2, 3, 4, 4)
mat <- a%*%t(a)

apply(mat, 2, function(x){as.integer((x/a)==a)})
Tino
  • 2,091
  • 13
  • 15
3

We can use outer to create a square matrix by comparing each element of the vector with the other elements

+(outer(v1, v1, `==`))

Or use sapply

+(sapply(v1, `==`, v1))
akrun
  • 874,273
  • 37
  • 540
  • 662