0

我目前正在处理通过 ODK(开放数据工具包)生成的 Stata 数据集。有一个选项可以回答多个答案的问题。例如,在我的问卷“您拥有哪些资产?” 面试官从 20 个选项中标记了所有答案。这为我生成了一个字符串变量,其内容例如

 "1 2 3 5 11 17 20"
 "3 4 8 9 11 14 15 18 20"
 "1 3 9 11"

由于这对于数百名参与者来说很难分析,我想生成新变量,为每个答案选项创建一个 1 或 0。对于变量,hou_as我尝试使用以下代码生成变量等hou_as_1hou_as_2

foreach p in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 {
local P : subinstr local p "-" ""
gen byte hou_as_`P' = strpos(hou_as, "`p'") > 0
}

对于单个数字,这会带来一个问题,即hou_as_1如果没有选择选项 1,如果填充了 10 11 12 ... 19 中的任何一个,变量也会填充 1。hou_as_2勾选选项 2、12 或 20 时同样填写。我怎样才能避免这个问题?

4

1 回答 1

1

您需要 20 个指标或虚拟变量。forval首先请注意,使用循环 1(1)20要容易得多,例如

forval j = 1/20 { 
    gen hou_as_`j' = 0
} 

将 20 个这样的变量初始化为 0。

我认为循环你的答案变量的单词更容易,单词在这里只是用空格分隔的。最多20个字,有点粗略但应该够快了

forval j = 1/20 { 
    forval k = 1/20 { 
        replace hou_as_`j' = 1 if word(hou_as, `k') == "`j'" 
    }
} 

让我们把它放在一起并在你的例子中尝试一下:

clear 
input str42 hou_as 
 "1 2 3 5 11 17 20"
 "3 4 8 9 11 14 15 18 20"
 "1 3 9 11"
end 

forval j = 1/20 { 
    gen hou_as_`j' = 0
    forval k = 1/20 { 
        replace hou_as_`j' = 1 if word(hou_as, `k') == "`j'" 
    }
} 

只是为了表明它有效:

. list in 3 

     +----------------------------------------------------------------------------+
  3. |   hou_as | hou_as_1 | hou_as_2 | hou_as_3 | hou_as_4 | hou_as_5 | hou_as_6 |
     | 1 3 9 11 |        1 |        0 |        1 |        0 |        0 |        0 |
     |----------+----------+----------+----------+----------+----------+----------|
     | hou_as_7 | hou_as_8 | hou_as_9 | hou_a~10 | hou_a~11 | hou_a~12 | hou_a~13 |
     |        0 |        0 |        1 |        0 |        1 |        0 |        0 |
     |----------+----------+----------+----------+----------+----------+----------|
     | hou_a~14 | hou_a~15 | hou_a~16 | hou_a~17 | hou_a~18 | hou_a~19 | hou_a~20 |
     |        0 |        0 |        0 |        0 |        0 |        0 |        0 |
     +----------------------------------------------------------------------------+

顺便说一句,你的线

local P : subinstr local p "-" ""

没有任何用处。本地宏p只包含整数数字的内容,因此根本不需要删除标点符号。

另请参阅此说明

. search multiple responses, sj

Search of official help files, FAQs, Examples, SJs, and STBs

SJ-5-1  st0082  . . . . . . . . . . . . . . . Tabulation of multiple responses
        (help _mrsvmat, mrgraph, mrtab if installed)  . . . . . . . .  B. Jann
        Q1/05   SJ 5(1):92--122
        introduces new commands for the computation of one- and
        two-way tables of multiple responses

SJ-3-1  pr0008   Speaking Stata: On structure & shape: the case of mult. resp.
        . . . . . . . . . . . . . . . . . . . . . . . .  N. J. Cox & U. Kohler
        Q1/03   SJ 3(1):81--99                                   (no commands)
        discussion of data manipulations for multiple response data
于 2017-10-03T10:11:54.923 回答