id x
1. A G
2. B F
3. C E
4. D D
5. E C
6. F B
7. G A
8. end
.
. gen n=1
.
. reshape wide @n,i(id) j(x) str
(note: j = A B C D E F G)
Data long -> wide
-----------------------------------------------------------------------------
Number of obs. 7 -> 7
Number of variables 3 -> 8
j variable (7 values) x -> (dropped)
xij variables:
n -> An Bn ... Gn
-----------------------------------------------------------------------------
.
. **********************************
. replace n=_n
(3 real changes made)
. reshape long id,i(n) j(t)
(note: j = 1 2)
Data wide -> long
-----------------------------------------------------------------------------
Number of obs. 4 -> 8
Number of variables 3 -> 3
j variable (2 values) -> t
xij variables:
id1 id2 -> id
-----------------------------------------------------------------------------
.
. **************************************************
. reshape wide @n,i(id1) j(id2) str
(note: j = A B C E F G H)
Data long -> wide
-----------------------------------------------------------------------------
Number of obs. 49 -> 7
Number of variables 3 -> 8
j variable (7 values) id2 -> (dropped)
xij variables:
n -> An Bn ... Hn
-----------------------------------------------------------------------------
. rename *n *
. list
+---------------------------------+
| id1 A B C E F G H |
|---------------------------------|
1. | A 0 0 0 0 0 1 1 |
2. | B 0 0 0 0 1 0 0 |
3. | C 0 0 0 1 0 0 0 |
4. | E 0 0 0 0 0 0 0 |
5. | F 0 0 0 0 0 0 0 |
6. | G 0 0 0 0 0 0 0 |
7. | H 0 0 0 0 0 0 0 |
+---------------------------------+
clear all
inp str10 v1 str10 v2
"a b c" "a"
"d e f" "b"
"g h i" "c"
"a" "a b c"
"b" "d e f"
"c" "g h i"
"d" "e"
end
preserve
g i=_n
reshape long v,i(i) j(j)
collapse (count)i, by(v)
mat m=J(_N,_N,0)
levelsof v,l(v)
mat rown m=`v'
mat coln m=`v'
restore
forv i=1/`=_N'{
mat m[rownumb(m, v1[`i']),colnumb(m, v2[`i'])]=1
}
n mat l m