I'm attempting to create a new variable in my dataset that stores a number, which is derived from a computation on another number from the same observation.
* Here is what my dataset looks like:
SubjectID Score MyNewScore
1001 5442822 0
1002 6406134 0
1003 16 0
Now, the variable Score is the sum of up to 23 distinct numbers (I'll call them "Responses"), ranging from 1 to 8,388,608.
/* Example of response values
1st response = 1
2nd response = 2
3rd response = 4
4th response = 8
5th response = 16
6th response = 32
...
23rd response = 8,388,608
*/
MyNewScore contains a count of these distinct responses used to obtain the value in Score. In my example dataset, MyNewScore should equal 9 as there are 9 responses used to arrive at a sum of 5,442,822.
I have nested a forvalues loop within a while loop in Stata that successfully calculates MyNewScore but I do not know how to replace the 0 that currently exists in the dataset with the result of my nested-loops.
Stata code used to calculate the value I'm after:
// Build a loop to create a Roland Morris Score
local score = 16
local count = 0
while `score' != 0 {
local ItemCode
forvalues i=1/24
local j = 2^(`i' - 1)
if `j' >= `score' continue, break
local ItemCode `j'
* display "`ItemCode'"
}
local score = `score' - `ItemCode'
if `score' > 1 {
local count = `count' + 1
display "`count'"
}
else if `score' == 1 {
local count = `count' + 1
display "`count'"
continue, break
}
}
How do I replace the 0s in MyNewScore with the output from the nested-loops? I have tried nesting these two loops in another while loop, with a `replace' command although that simply applies the count from the first observation, to all observations in the dataset.