使用循环替换变量的值

时间:2017-05-05 18:10:36

标签: stata

我正在尝试在我的数据集中创建一个存储数字的新变量,该数字来自同一观察中另一个数字的计算。

* Here is what my dataset looks like:
SubjectID    Score     MyNewScore
1001         5442822   0
1002         6406134   0
1003         16        0

现在,变量Score是最多23个不同数字的总和(我称之为“响应”),范围从1到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包含用于获取Score中的值的这些不同响应的计数。在我的示例数据集中,MyNewScore应该等于9,因为有9个响应用于得到5,442,822的总和。

我已经在Stata的forvalues循环中嵌套while循环,成功计算MyNewScore但我不知道如何用我的嵌套结果替换数据集中当前存在的0 -loops。

Stata代码用于计算我之后的值:

// 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
    }
}

如何使用嵌套循环的输出replace MyNewScore中的0?我尝试将这两个循环嵌套在另一个while循环中,使用`replace'命令,尽管它只是将第一次观察的计数应用于数据集中的所有观察。

2 个答案:

答案 0 :(得分:1)

我认为第23个回复的值存在错误,应为2^(23-1),即4,194,304。

前4个回答的总和是15;这是1+2+4+82^4-1。所有23个回复的总和为2^23 - 1,因此得分的最大可能值为8,388,607。

这里不需要循环观察。您可以从Score变量的克隆副本开始。循环遍历每个响应,从最高向下开始到1.在每次通过时,如果当前分数高于或等于响应的值,则计算该响应并从分数中减去该值。

* Example generated by -dataex-. To install: ssc install dataex
clear
input long(SubjectID Score)
1001 5442822
1002 6406134
1003      16
1004       1
1005      19
1006      15
1007 8388607
end

clonevar x = Score
gen wanted = 0
qui forvalues i=23(-1)1 {
    local response = 2^(`i'-1)
    replace wanted = wanted + 1 if x >= `response'
    replace x = x - `response' if x >= `response'
}

答案 1 :(得分:0)

我认为您需要做的就是将代码嵌套在遍历数据集中每个变量的循环中,如下所示:

// get total number of observations in dataset
local N = _N 

// go through each observation and run the while loop
forvalues observation = 1/`N' {
    local score = Score[`observation']
    local count = 0

    // your while loop here
    while `score' != 0 {
        ...
    }

    replace MyNewScore = `ItemCode' in `observation' // (or whatever value you're after)
}

这是你之后的事吗?

相关问题