在Stata中拆分字符串变量,并按顺序放置值

时间:2016-06-04 16:57:48

标签: stata

在Stata中拆分字符串变量通常很容易。但是,在我的情况下,我无法重新组织这些值的顺序。变量表示与观察相关的特征列表,如下所示:

Variable_Name
No Phosphates
No Perfumes; No Phosphates; Private Label
No Perfumes; Private Label
Private Label

如果我使用代码split Variable_Name, p("; "),我会

Variable_Name1      Variable_Name2      Variable_Name2 
No Phosphates              
No Perfumes         No Phosphates       Private Label
No Perfumes         Private Label       
Private Label

如何重新排列值,使其看起来像这样?

Variable_Name1      Variable_Name2        Variable_Name3        
No Phosphates              
No Phosphates       No Perfumes            Private Label
                    No Perfumes            Private Label      
                                           Private Label

换句话说,如何在同一列下对相同的特征进行分组?

这是完整的代码:

clear
input str50 Variable_Name 
"No Phosphates"
"No Perfumes; No Phosphates; Private Label"
"No Perfumes; Private Label"
"Private Label"
end

split Variable_Name, p("; ")

挑战在于我的特征数量未知。我不可能手动识别它们并将它们分类到列中,或者查找某些字符串值。

1 个答案:

答案 0 :(得分:2)

有关reshape技术,请参阅here。请注意,这对拼写等方面的细微差别完全敏感。

clear 
input str100 what 
"No Phosphates"
"No Perfumes; No Phosphates; Private Label"
"No Perfumes; Private Label"
"Private Label"
end 
split what, p(;) 
rename what original 
gen id = _n
reshape long what, i(id) 
replace what = trim(what) 
egen group = group(what) 
drop if missing(group) 
drop _j 
reshape wide what, i(id) j(group) 
list