Reputation: 781
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 !
Upvotes: 1
Views: 921
Reputation: 2101
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)})
Upvotes: 4
Reputation: 887911
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))
Upvotes: 3