我想在将数据集从长到宽重塑后保留变量标签。我在输入数据集时遇到问题(我在 Excel 中键入它们然后导入)。
clear
set obs 7
input id a1 a2 a3
"s001" "John" 23 "Primary"
"s002" "Mary" 32 "Secondary"
"s002" "Anna" 23 "Tertiary"
"s003" "Joseph" 34 "Secondary"
"s003" "Oganyo" 23 "Primary"
"s004" "Manyoya" 34 "Tertiary"
"s005" "Makbuti" 45 "Primary"
end
*======= Label the variables
label var a1 "partners name"
label var a2 "partners age"
label var a3 "partners education"
foreach variable of varlist a*{
local varlabel : variable label `variable'
di "`varlabel'"
bys id: gen index = _n
renvars a* , postfix(_)
reshape wide a*, i(id) j(index)
label var `variable'* "`varlabel'"
}
这里的代码非常混乱,如果不进行大手术,就无法正常工作。
一开始,input
语句无法在需要时声明字符串变量。
set obs 7
与input
的end
兼容。
一个大问题是您正在循环一堆命令,包括reshape
,但只有一个reshape
要执行。
用于保存变量标签的代码需要单独保存。
renvars
来自Stata Journal(2005),这里似乎不需要任何方式。从Stata 12(2011!)开始,它应该仍然有效,但基本上被rename
的扩展所取代。
这是我对您应该给出的示例和您需要的代码的最佳猜测。
clear
input str4 id str7 a1 a2 str9 a3
"s001" "John" 23 "Primary"
"s002" "Mary" 32 "Secondary"
"s002" "Anna" 23 "Tertiary"
"s003" "Joseph" 34 "Secondary"
"s003" "Oganyo" 23 "Primary"
"s004" "Manyoya" 34 "Tertiary"
"s005" "Makbuti" 45 "Primary"
end
label var a1 "partner's name"
label var a2 "partner's age"
label var a3 "partner's education"
local j = 0
foreach variable of varlist a* {
local ++j
local varlabel`j' : variable label `variable'
di "`varlabel`j''"
}
bys id: gen index = _n
reshape wide a*, i(id) j(index)
forval j = 1/3 {
foreach v of var a`j'* {
label var `v' "`varlabel`j''"
}
}
list
describe
下面是最后两个命令的输出。
. list
+------------------------------------------------------------+
| id a11 a21 a31 a12 a22 a32 |
|------------------------------------------------------------|
1. | s001 John 23 Primary . |
2. | s002 Mary 32 Secondary Anna 23 Tertiary |
3. | s003 Joseph 34 Secondary Oganyo 23 Primary |
4. | s004 Manyoya 34 Tertiary . |
5. | s005 Makbuti 45 Primary . |
+------------------------------------------------------------+
.
. describe
Contains data
Observations: 5
Variables: 7
------------------------------------------------------------------------------------------------------------------
Variable Storage Display Value
name type format label Variable label
------------------------------------------------------------------------------------------------------------------
id str4 %9s
a11 str7 %9s partner's name
a21 float %9.0g partner's age
a31 str9 %9s partner's education
a12 str7 %9s partner's name
a22 float %9.0g partner's age
a32 str9 %9s partner's education
------------------------------------------------------------------------------------------------------------------
Sorted by: id
注意:reshape wide
使Stata中的大多数事情变得更加困难。
注意:请使用dataex
在Stata中创建可重现的数据示例。