Adriana escobar
Adriana escobar

Reputation: 21

Generating a composite date variable

I want to generate a variable month that has the month and year together as 2013M01.

Below is a sample of my data:

clear

input expected_arrival_month year
1 2013
2 2014
3 2015
4 2016
5 2017
6 2018
end

I tried the following command:

generate month = .
replace month = 2013M01 if expected_arrival_month == 1 & year == 2013

However, I received the error:

2013M01 invalid name 
r(198)

How can I get the desired output?

Upvotes: 1

Views: 266

Answers (2)

Damian Clarke
Damian Clarke

Reputation: 106

The issue here is in dealing with string rather than numeric variables. Given that the variable you are generating is a string variable, the contents of the variable must be enclosed in quotation marks:

generate month = "2013M01" if expected_arrival_month == 1 & year == 2013

There would also be other more efficient ways to deal with this generation, for example using Stata's egen command (and concat), or datetime functions as indicated in another response.

Upvotes: 0

Nick Cox
Nick Cox

Reputation: 37208

For essentially all Stata purposes a numeric monthly date variable is better than anything hand- or homemade (and certainly than dates held as string variables). You can get such variables to appear as you ask. You certainly do not need to calculate individual values directly. Although this code is for a minimal dataset it will apply to all values in numeric variables as you describe. See help datetime for invaluable (and unavoidable) information.

clear
set obs 1 
generate year = 2013 
generate arrival_month = 1 

generate wanted = ym(year, arrival_month)
format wanted %tmCCYY!MNN 

list 

     +---------------------------+
     | year   arriva~h    wanted |
     |---------------------------|
  1. | 2013          1   2013M01 |
     +---------------------------+

(As commented, you should provide example data directly and in a way that makes variable types clear. If one or both variables are really string, apply destring first or use monthly().)

Upvotes: 1

Related Questions