将复合变量拆分为两个变量

Splitting a composite variable into two variables

我有一个名为 countrystring 变量,其值可以是 Afghanistan2008,但也可以是 Brasil2012。我想创建两个新变量,一个是国家部分,一个是年份部分。

因为 string 的末尾总是有数字,所以我知道 string 应该从右侧而不是左侧拆分的位置。

我可以使用类似的东西吗:

gen(substr("country",-4,.))

如果没有,谁能告诉我如何将一整列此类变量拆分为一个 country 和一个 year 变量?我也想保留原来的变量。

对于我的具体情况,下面创建了一个新的 year 变量:

gen spyear = real(substr(country,-4,.))

我从@PearlySpencer 那里拿走了另一部分:

generate len = length(country) - 3
generate spcountry = substr(country, 1, len - 1)

创建要删除的多余列。

编辑(Nick Cox)这可以简化为

gen spyear = real(substr(country, -4, 4)) 
gen spcountry = substr(country, 1, length(country) - 4)

显示

  1. 无需创建包含字符串长度的变量。

  2. 也不需要令人费解的拆分 4 = 3 + 1。

您可以使用正则表达式

clear
set obs 2

generate string = ""
replace string = "Afghanistan2008" in 1
replace string = "Brasil2012" in 2

generate country = regexs(0) if regex(string, "[a-zA-Z]+")
generate year = regexs(1) + regexs(2) if regex(string, "(19|20)([0-9][0-9])")

list

   +--------------------------------------+
   |          string       country   year |
   |--------------------------------------|
1. | Afghanistan2008   Afghanistan   2008 |
2. |      Brasil2012        Brasil   2012 |
   +--------------------------------------+

在 Stata 的命令提示符中键入 help regex 以获取更多信息。

或者您可以执行以下操作:

generate len = length(string) - 3

generate country2 = substr(string, 1, len - 1)
generate year2 = substr(string, len, .)

list country2 year2

   +---------------------+
   |    country2   year2 |
   |---------------------|
1. | Afghanistan    2008 |
2. |      Brasil    2012 |
   +---------------------+