0
votes

I'm working with a data set that contains 40 different participants, with each 30 observations. As I am observing search behavior, I want to calculate the search distance for each subject per round (from 1 to30).

In order to compare my data with current literature, I need to use the Hamming distance to describe search distances.

The variable is called Inputs and is a string variable with binary inputs 0 or 1 with a length of 10. E.g: Input Type 1 Subject 1 Round 1: 0000011111 Input Type 1 Subject 1 Round 2: 0000011110

Using the Levensthein distance, my approach was simple:

sort type_num Subject round_num
gen input_prev=Input[_n-1]
replace input_prev="0000000000" if round_num==1 //default starting position with 0000000000 to get search distance for first input in round 1

//Levensthein distance & clearing data (Levensthein instead of hamming distance)
ustrdist Input input_prev
rename strdist input_change

I am now struggling with getting the right Stata commands for the Hamming distance. Can someone help?

1
You should show the code you tried. - Nick Cox

1 Answers

0
votes

Does this help? As I understand it, Hamming distance is the count of characters (bits) that differ at corresponding positions of strings of equal length. So, given two variables and wanting comparisons within each observation, it is just a loop over the characters.

clear
set obs 10
set seed 2803 

* sandbox 
quietly forval j = 1/2 {
    gen test`j' = ""
    forval k = 1/10 {
        replace test`j' = test`j' + strofreal(runiform() > (`j' * 0.3))
    }
}

set obs 12 
replace test1 = 10 * "1" in 11 
replace test2 = test1 in 11
replace test1 = test1[11] in 12 
replace test2 = 10 * "0" in 12 

* calculation
gen wanted = 0
quietly forval k = 1/10 {
    replace wanted = wanted + (substr(test1, `k', 1) != substr(test2, `k', 1))
}

list 

     +----------------------------------+
     |      test1        test2   wanted |
     |----------------------------------|
  1. | 1110001111   1001101000        7 |
  2. | 1111011011   1101011111        2 |
  3. | 1011001111   1110110111        5 |
  4. | 0000111011   1011010100        8 |
  5. | 1011011011   1111100110        6 |
     |----------------------------------|
  6. | 0011111100   0100011110        5 |
  7. | 0011011011   0011111010        2 |
  8. | 1010100011   1011000100        5 |
  9. | 1110011011   1010010100        5 |
 10. | 1001011111   0100111001        6 |
     |----------------------------------|
 11. | 1111111111   1111111111        0 |
 12. | 1111111111   0000000000       10 |
     +----------------------------------+