将字符串月份转换为数字
Convert string month to numeric
我有一个变量 period
,其中包含作为缩写字符串的月份(即 "JAN"
、"FEB"
、"MAR"
等)。如何将 period
转换为数字(即 1
、2
、3
等)?
我的解决方案是:
gen fake_date_s = "2000"+period+"1"
gen fake_date = date(fake_date_s, "YMD")
gen month = month(fake_date)
我觉得不丑:
clear
input ///
str3 period
JAN
FEB
DEC
end
list
gen monthnum = month(date("2000" + period + "1", "YMD"))
list
这也有效:
gen monthnum = month(date(period, "M"))
因为它将每日日期中的日期和年份设置为 01
和 1960
,默认情况下。
我相信您可以找到不使用日期函数的替代方法,但为什么不使用它们呢?
另一种方法是:
local i=1
foreach m in `c(Mons)' {
replace month = "`i'" if month == upper("`m'")
local ++i
}
destring month, replace
我有一个变量 period
,其中包含作为缩写字符串的月份(即 "JAN"
、"FEB"
、"MAR"
等)。如何将 period
转换为数字(即 1
、2
、3
等)?
我的解决方案是:
gen fake_date_s = "2000"+period+"1"
gen fake_date = date(fake_date_s, "YMD")
gen month = month(fake_date)
我觉得不丑:
clear
input ///
str3 period
JAN
FEB
DEC
end
list
gen monthnum = month(date("2000" + period + "1", "YMD"))
list
这也有效:
gen monthnum = month(date(period, "M"))
因为它将每日日期中的日期和年份设置为 01
和 1960
,默认情况下。
我相信您可以找到不使用日期函数的替代方法,但为什么不使用它们呢?
另一种方法是:
local i=1
foreach m in `c(Mons)' {
replace month = "`i'" if month == upper("`m'")
local ++i
}
destring month, replace