状態の省略形を指定して、状態fipsコードに等しい変数を設定しようとしています。これを行うためのより短い方法はありますか:
fips = "[fips code]" if other_variable == "[state_abbrev]"
私は現在50行あります。ループを作成したいのですが、値が2つ変化していることを考えると、すべての順列をループしないようにする方法がわかりません。
明らかな近道はありませんが、Stataでは
. search merge, faq
キットバウムによる関連するFAQを見つけるため。
これはFAQでカバーされている戦略の例です。
1)状態名と関連するfipsコードの2つの変数を含むデータセットを作成します。これを少し柔軟にするために、州名の一般的な半略語を含めます。将来的には、2文字の状態の省略形を含む3番目の変数を追加する可能性があります。
clear
input fips str20 state
1 "alabama"
2 "alaska"
4 "arizona"
5 "arkansas"
6 "california"
8 "colorado"
9 "connecticut"
10 "delaware"
11 "district of columbia"
12 "florida"
13 "georgia"
15 "hawaii"
16 "idaho"
17 "illinois"
18 "indiana"
19 "iowa"
20 "kansas"
21 "kentucky"
22 "louisiana"
23 "maine"
24 "maryland"
25 "massachusetts"
26 "michigan"
27 "minnesota"
28 "mississippi"
29 "missouri"
30 "montana"
31 "nebraska"
32 "nevada"
33 "new hampshire"
34 "new jersey"
35 "new mexico"
36 "new york"
37 "north carolina"
37 "n. carolina"
38 "north dakota"
38 "n. dakota"
39 "ohio"
40 "oklahoma"
41 "oregon"
42 "pennsylvania"
44 "rhode island"
45 "south carolina"
45 "s. carolina"
46 "south dakota"
46 "s. dakota"
47 "tennessee"
48 "texas"
49 "utah"
50 "vermont"
51 "virginia"
53 "washington"
54 "west virginia"
54 "w. virginia"
55 "wisconsin"
56 "wyoming"
72 "puerto rico"
end
save statefips, replace
2)状態名を持つ変数を保持するプライマリデータセットをロードし、を使用して多対1のマージを実行しstatefips.dta
ます。
sysuse census, clear
// Convert the state names to lowercase to ensure
// consistency with the statefips dataset
replace state = lower(state)
merge m:1 state using statefips.dta
drop if _merge == 2
drop _merge
マスターデータセットの状態名の大文字と小文字を保持したい場合は、一時変数を生成し、それをマージに使用できます。
gen statelower = lower(state)
merge m:1 statelower using statefips.dta
また、statefips.dta
データセットを作成したら、マージを実行するたびにデータセットを再作成する必要はありません。プロジェクトのファイルと一緒にバンドルして、必要に応じて使用することができます。2文字の状態の略語を追加したり、その他の変更を加えたりする場合は、それを再作成するのは事実上瞬時です。