1

I have a vector, say

1
0
1
1
1
0

denoting gender. I want to matricise this vector into an square matrix and for every pair perform a function. So say I want to sum.

2 1 2 2 2 1
1 0 1 1 1 0
2 1 2 2 2 1
2 1 2 2 2 1
2 1 2 2 2 1
1 0 1 1 1 0

Or if the rule is ‘similar is a 1’

1 0 1 1 1 0
0 1 0 0 0 1
1 0 1 1 1 0
1 0 1 1 1 0
1 0 1 1 1 0
0 1 0 0 0 1

How can I create such a square matrix from a vector/column c(1,0,1,1,1,0)?

I have been manipulating numerous vectors but I keep on getting errors.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Ceebeekay
  • 11
  • 1
  • I suspect you want `?outer`, as in `outer(x,x,FUN=\`+\`)` but i'm not sure I follow your second example output. What does ‘*similar is a 1*’ mean? – thelatemail Jun 11 '19 at 22:59
  • Sorry for the lack of clarity. It would be boolean for example so if we compare row 1 with column 3 both are 1 so it becomes 1 as they are similar. However row 1 compared to column 2 becomes a 0 because 1 is dissimilar to 0. – Ceebeekay Jun 11 '19 at 23:38
  • 1
    Sounds like `outer` is definitely what you want then- `outer(x,x,FUN=\`==\`) + 0` – thelatemail Jun 12 '19 at 00:18
  • Possible duplicate of https://stackoverflow.com/questions/5438632/mapply-basics-how-to-create-a-matrix-from-two-vectors-and-a-function or even https://stackoverflow.com/questions/38935146/apply-function-over-two-vectors-of-different-lengths-and-return-a-matrix-in-r – thelatemail Jun 12 '19 at 00:20
  • 1
    `outer(x,x,'+');outer(x,x,'==')` etc. You are looking for outer – Onyambu Jun 12 '19 at 00:26

0 Answers0