重新编码字符串变量
Recode A String Variable
input VAR1 VAR2
A1 1
A2 0
A3 1
A4 1
A5 1
A6 1
A7 1
A8 1
A9 1
A10 1
A15 1
B7 0
A1 0
A16 1
A17 1
A18 1
A19 1
A20 0
A21 1
end
假设您有显示的数据。我有 VAR1
并希望从中创建 VAR2
如果 VAR1
开头包含值 1:A1、A3-A10、A15-A19、A21,否则它是零。我相信为此你可以使用 strpos(VAR1)
但是否可以这样说: strpos(VAR1, "A1, A3/A10, A15/A19, A21")
?
如果您感兴趣的字符串数量较少,则可以使用以下方法。如果您正在搜索大量字符串,您可能需要另一种方法,而写出字符串范围(例如 A3-A10)是不可行的。
clear
input str3 VAR1 VAR2
A1 1
A2 0
A3 1
A4 1
A5 1
A6 1
A7 1
A8 1
A9 1
A10 1
A15 1
B7 0
A1 1
A16 1
A17 1
A18 1
A19 1
A20 0
A21 1
end
gen wanted = 0
local mystrings = "A1 A3 A4 A5 A6 A7 A8 A9 A10 A15 A16 A17 A18 A19 A21"
foreach string in `mystrings' {
replace wanted = 1 if strpos(VAR1, "`string'") == 1
}
assert wanted == VAR2
请注意,在您的示例输入中,第二次出现的 A1 的值为 0,但根据您的 post.
,其值应为 1
这是一个适用于更大范围字符串的更通用的解决方案:
gen A = 0
replace A = 1 if strpos(VAR1,"A") == 1
gen newvar = substr(VAR1,2,.)
destring newvar, replace
gen wanted = 0
replace wanted = 1 if A == 1 & (inlist(newvar,1,21) | inrange(newvar,3,10) | inrange(newvar,15,19))
assert wanted == VAR2
input VAR1 VAR2
A1 1
A2 0
A3 1
A4 1
A5 1
A6 1
A7 1
A8 1
A9 1
A10 1
A15 1
B7 0
A1 0
A16 1
A17 1
A18 1
A19 1
A20 0
A21 1
end
假设您有显示的数据。我有 VAR1
并希望从中创建 VAR2
如果 VAR1
开头包含值 1:A1、A3-A10、A15-A19、A21,否则它是零。我相信为此你可以使用 strpos(VAR1)
但是否可以这样说: strpos(VAR1, "A1, A3/A10, A15/A19, A21")
?
如果您感兴趣的字符串数量较少,则可以使用以下方法。如果您正在搜索大量字符串,您可能需要另一种方法,而写出字符串范围(例如 A3-A10)是不可行的。
clear
input str3 VAR1 VAR2
A1 1
A2 0
A3 1
A4 1
A5 1
A6 1
A7 1
A8 1
A9 1
A10 1
A15 1
B7 0
A1 1
A16 1
A17 1
A18 1
A19 1
A20 0
A21 1
end
gen wanted = 0
local mystrings = "A1 A3 A4 A5 A6 A7 A8 A9 A10 A15 A16 A17 A18 A19 A21"
foreach string in `mystrings' {
replace wanted = 1 if strpos(VAR1, "`string'") == 1
}
assert wanted == VAR2
请注意,在您的示例输入中,第二次出现的 A1 的值为 0,但根据您的 post.
,其值应为 1这是一个适用于更大范围字符串的更通用的解决方案:
gen A = 0
replace A = 1 if strpos(VAR1,"A") == 1
gen newvar = substr(VAR1,2,.)
destring newvar, replace
gen wanted = 0
replace wanted = 1 if A == 1 & (inlist(newvar,1,21) | inrange(newvar,3,10) | inrange(newvar,15,19))
assert wanted == VAR2