Announcement

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

  • Reshaping to long form having issues

    I have a dataset that has a column that is month_day (so 365 rows) and then each column heading is a year 1994 - 2004. I put a letter in front of each year so that the headings are A_1994, B_1995 through E_2024. i entered this:
    reshape long A_1994 B_1995 C_1996 D_1997 E_1998 F_1999 G_2000 H_2001 I_2002 J_2003 K_2004 L_2005 M_2006 N_2007 O_2008 P_2009 Q_2010 R_2011 S_2012 T_2013 U_2014 V_2015 W_2016 X_2017 Y_2018 Z_2019 A_2020 B_2021 C_2022 D_2023 E_2024, i(month_day) j(year) string

    I've also created a varlist for these variables and tried reshape long `varlist', i(month_day) j(year) string (with and without string) but get the same error, which is as follows:

    no xij variables found
    You typed something like reshape wide a b, i(i) j(j).
    reshape looked for existing variables named a# and b# but could not find any.

    Thanks for any help you can provide,
    Janet

  • #2
    reshape long wants stubs, not variable names. The prefixes A ... Z need to be replaced by a common stub.

    The data example here is just silly in part, but I use your variable names and show some technique.

    Code:
    * sandbox with same variable names
    clear
    set obs 30
    gen month_day = _n
    
    foreach v in A_1994 B_1995 C_1996 D_1997 E_1998 F_1999 G_2000 H_2001 I_2002 J_2003 K_2004 L_2005 M_2006 N_2007 O_2008 P_2009 Q_2010 R_2011 S_2012 T_2013 U_2014 V_2015 W_2016 X_2017 Y_2018 Z_2019 A_2020 B_2021 C_2022 D_2023 E_2024 {
          gen `v' = 42  
    }
    
    * there is likely to be a way to do this without a loop, but this works .
    forval y = 1994/2024 {
          rename ?_`y' data`y'
    }
    
    * now you can reshape
    reshape long data, i(month_day) j(year)
    Last edited by Nick Cox; 03 Feb 2025, 18:48.

    Comment


    • #3
      * there is likely to be a way to do this without a loop, but this works .
      forval y = 1994/2024 {
      rename ?_`y' data`y'
      }
      Yes, there is:

      Code:
      rename (*_#) data#, renumber(1994)

      Comment


      • #4
        Or
        Code:
        rename ?_# data#[2]
        (I find the renumber option here unintuitive, since no actual renumbering is needed)

        Comment


        • #5
          Thanks to Clyde Schechter and Hemanshu Kumar for the loop-free solutions. It was less effort for me in this case to write a loop!

          Comment

          Working...
          X