Stata中使用inlist()函数出现'type mismatch'错误的技术求助
解决Stata中'type mismatch'错误的方案
问题根源
触发type mismatch错误的核心原因是:education变量的类型与你在inlist()中使用的匹配值类型不兼容——要么education是数值型变量(用数字编码代表学历),要么字符串匹配时存在格式不一致问题。
分步解决
1. 先确认education的变量类型
运行命令查看变量属性:
describe education
- 若结果显示
type: numeric,说明是数值型变量,不能直接和字符串匹配; - 若显示
strXX(如str80),则为字符串型变量,需排查格式问题。
2. 处理数值型education
如果education是数值型,先通过以下命令获取学历对应的编码:
label list // 查看变量标签与编码的对应关系 tab education, nolabel // 直接显示原始编码分布
假设编码对应关系为:7=Level7学位、8=Level8学位、9=Level9学位、10=Level10学位,修改生成变量的代码为:
gen edu_degree = 1 if inlist(education, 7, 8, 9, 10)
3. 处理字符串型education
如果education是字符串型,先清理可能存在的空格、大小写差异问题:
replace education = trim(education) // 去除字符串前后空格
然后执行生成变量的命令(注意不要重复用gen,否则会提示变量已存在):
gen edu_degree = 1 if inlist(education, "Bachelor's Degree/Occupational Certificate - NQF Level 7", "Honours Degree/Postgraduate Diploma/Occupational Certificate - NQF Level 8", "Post Higher Diploma (M Tech and Master's Degree) - NQF Level 9", "Doctoral Degrees (D-Tech and PhD) - NQF Level 10") replace edu_degree = 0 if missing(edu_degree) // 可选:给不符合条件的样本赋值0
4. 统计目标人群数量
生成变量后,用以下命令统计各类学位的人数:
tab education if edu_degree == 1 // 按学历分类统计符合条件的样本数 count if edu_degree == 1 // 统计所有符合条件的总人数
内容的提问来源于stack exchange,提问作者Kay
相关产品推荐
相关产品推荐

