Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • converting date variables to string

    Dear Stata experts,

    I struggle with a dataset from Bureau of Economic Analysis. I downloaded Excel file with quarterly US GDP. I imported it into Stata. Here is my data example:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str1 A str30 B double(C D E F G) int H
    "1" "        Gross domestic product" 10002.2 10247.7 10318.2 10435.7 10470.2 10599
    end

    I came up with the idea to rename variables A-CP to 2000q1-2022q4 and then reshape it. I used the codes:

    Code:
    set obs 92
    
    gen time=tq(1999q4) + _n
    
    format time %tq
    
    levelsof time, local(times)
    foreach time of local times{
    foreach var of varlist C-CP{
        rename `var' `time'
    }
    }
    I have an error: 1 new variable name invalid
    You attempted to rename C to 160.
    That is an invalid Stata variable name.


    I understood that even though Stata displays time as e.g. 2000q1 it is 160. I don't know how to convert it to string variable "2000q1". When I use code tostring Stata converts it to "160".

    Please help me


  • #2
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str1 A str30 B double(C D E F G) int H
    "1" "        Gross domestic product" 10002.2 10247.7 10318.2 10435.7 10470.2 10599
    end
    
    rename (C-H) gdp#, addnumber(1)
    reshape long gdp, i(A B) j(quarter)
    replace quarter= quarter + `=tq(1999q4)'
    format quarter %tq
    Res.:

    Code:
    . l, sep(0)
    
         +--------------------------------------------------------+
         | A                                B   quarter       gdp |
         |--------------------------------------------------------|
      1. | 1           Gross domestic product    2000q1   10002.2 |
      2. | 1           Gross domestic product    2000q2   10247.7 |
      3. | 1           Gross domestic product    2000q3   10318.2 |
      4. | 1           Gross domestic product    2000q4   10435.7 |
      5. | 1           Gross domestic product    2001q1   10470.2 |
      6. | 1           Gross domestic product    2001q2     10599 |
         +--------------------------------------------------------+
    
    .

    Comment


    • #3
      Thank you Andrew for your help!

      Comment

      Working...
      X