Stata中检测用户输入变量数据类型的代码报错求助
Stata数据类型检测代码修正方案
问题场景
原代码意图对用户输入的内容进行数据类型分类,但执行时输入"hello"出现no variables defined错误,原代码及报错日志如下:
原代码
capture program drop smth program define smth di "Enter smth: " _request(smth1) local type = substr("`: type $smth1 '", 1, 3) if "`type'" == "str" { di "It is a string!" } else if "`type'" == "flo" { di "It is a float!" } else if "`type'" == "int" { di "It is an integer!" } else { di "it is not a string, float nor integer!" } end
报错日志
. do trialscript . capture program drop smth . program define smth 1. di "Enter smth: " _request(smth1) 2. local type = substr("`: type $smth1 '", 1, 3) 3. if "`type'" == "str" { 4. di "It is a string!" 5. } 6. else if "`type'" == "flo" { 7. di "It is a float!" 8. } 9. else if "`type'" == "int" { 10. di "It is an integer!" 11. } 12. else { 13. di "it is not a string, float nor integer!" 14. } 15. end . . end of do-file . smth Enter smth: . hello no variables defined it is not a string, float nor integer!
错误原因
- 宏引用错误:
_request将用户输入存储为局部宏,原代码用$smth1引用全局宏,正确引用应为`smth1'。 - 逻辑偏差:
: type命令用于检测数据集中已存在的变量类型,但用户输入的"hello"是具体值而非变量名,Stata找不到对应变量因此报错。
修正方案
根据需求分两种场景处理:
场景1:检测数据集中的变量类型
若需求是让用户输入变量名,检测该变量在当前数据集中的类型,修正代码如下:
capture program drop check_var_type program define check_var_type di "Enter variable name: " _request(varname) // 先判断变量是否存在 capture confirm variable `varname' if _rc { di "Error: Variable `varname' does not exist in the dataset!" exit } // 获取变量类型并截取前3位 local type = substr("`: type `varname''", 1, 3) if "`type'" == "str" { di "It is a string variable!" } else if "`type'" == "flo" { di "It is a float variable!" } else if "`type'" == "int" { di "It is an integer variable!" } else { di "It is not a string, float nor integer variable!" } end
场景2:检测用户直接输入的值的类型
若需求是让用户输入具体值,检测该值的类型(字符串/整数/浮点),修正代码如下:
capture program drop check_value_type program define check_value_type di "Enter a value: " _request(input_val) // 判断是否为纯数字 capture confirm number `input_val' if !_rc { // 判断是否为整数 if `input_val' == int(`input_val') { di "It is an integer!" } else { di "It is a float!" } } else { di "It is a string!" } end
使用说明
- 场景1:先加载目标数据集,执行
check_var_type后输入数据集中已存在的变量名即可。 - 场景2:直接执行
check_value_type,输入任意值(如"hello"、123、45.67)即可正确判断类型。
内容的提问来源于stack exchange,提问作者Jason Chia Kim Leng
相关产品推荐
相关产品推荐

