如何在上传包含指定列的数据文件时使语句不区分大小写?

huangapple go评论69阅读模式
英文:

How to make statement case insensitive when uploading a dta file with specified columns?

问题

我想循环遍历不同的文件:

forvalues y=2014/2022 {
    use var1 var2 var3 using "file_`y'.dta"
    save "file2_`y'"
}

然而,其中一些文件的变量名是 VAR1 VAR2 var3 而不是 var1 var2 var3
我该如何使语句不区分大小写?

英文:

I want to loop through different files:

forvalues y=2014/2022 {
    use var1 var2 var3 using "file_`y'.dta"
    save "file2_`y'
}

However, some of the files have var names VAR1 VAR2 var3 instead of var1 var2 var3.
How do I make the statement case insensitive?

答案1

得分: 1

我不确定是否有一种简洁的方法来做这个,但以下是一个使用describecapture的示例,首先检查变量是否包含在.dta文件中。

首先创建包含不同大小写的简单数据示例:

tempfile the_data1 the_data2
clear
input var1 VAR2 var3
0 1 0
end 
save `the_data1', replace 

clear
input var1 var2 VAR3 // 请注意,大写与上述不同
0 1 0
end 
save `the_data2', replace 

然后,这个循环处理不同的名称。外部循环遍历两个文件,并创建一个空的本地变量myvarlist,其中将包含该文件的适当变量名称。capture行尝试对小写变量进行描述命令。如果成功(_rc==0),则将小写名称添加到列表中。如果失败(_rc!=0),则将大写名称添加到列表中。在遍历变量后,use行有效,因为所有情况都已经得到了更正。

forvalues i=1/2 {
    local myvarlist ""
    foreach myvar in var1 var2 var3 {
        capture noisily describe `myvar' using `the_data`i''
        if (_rc==0) local myvarlist "`myvar' `myvar'"
        if (_rc!=0) local myvarlist = "`myvarlist' " + upper("`myvar'")
    }
    use `myvarlist' using `the_data`i''
    describe 
    * 在此保存文件
}
英文:

I'm not sure there's a concise way to do this, but here's an example using describe and capture to first check if the variable is contained in the .dta file.

First make the simple data examples with different cases:

tempfile the_data1 the_data2
clear
input var1 VAR2 var3
0 1 0
end 
save `the_data1', replace 

clear
input var1 var2 VAR3 // note uppercase is different from above
0 1 0
end 
save `the_data2', replace 

Then this loop handles the different names. The outer loop goes through the two files and creates an empty local myvarlist which will contain the appropriate variable names for that file. The capture line tries a describe command of the lowercase variable. If it works (_rc==0), the lowercase name is added to the list. If it fails (rc!=0), the uppercase name is added to the list. After looping through the variables, the use line works because the cases have all been corrected.

forvalues i=1/2 {
	local myvarlist ""
	foreach myvar in var1 var2 var3 {
		capture noisily describe `myvar' using `the_data`i'' 
		if (_rc==0) local myvarlist "`myvarlist' `myvar'"
		if (_rc!=0) local myvarlist = "`myvarlist' " + upper("`myvar'")
	}
	use `myvarlist' using `the_data`i''
	describe 
    * Save file here
}

huangapple
  • 本文由 发表于 2023年3月20日 23:13:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定