Announcement

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

  • Help with <rename> multiple variables after reshape?

    Hi Stata community.
    I'm running Stata 18 on Windows.

    I've reshaped a data set long to wide so that my dataset contains <school id>, <person id>, and a list of 50 variables that are numerical scores to test questions. The 50 test questions belong to five groups - let's say apples, bananas, oranges, etc.

    I want the test questions (now in wide format) to be labeled "q_apple_1", "q_apple_2", "q_banana_1", etc. But after <reshape>, they're named "answer_valueq_apple_1", "answer_valueq_apple_2", etc. I need to get rid of "answer_value" (the original stub from my reshape) for all of the 50 variables/question values.

    I'm looking at the options in <rename> to get rid of that "answer_value" stem before the "q" for each item (there are question marks, wildcards, etc.) but I'm failing on finding the correct coding. If anyone can offer some tips, I would great appreciate it.

  • #2
    Something like this should work:

    Code:
    clear
    set obs 1
    input answer_valueq_apple_1 answer_valueq_apple_2 answer_valueq_apple_3
    end
    
    foreach var of varlist _all{
        local newname = subinstr("`var'", "answer_value", "", 1)
        rename `var' `newname'
    }
    list
    Code:
    . list
    
         +--------------------------------+
         | q_appl~1   q_appl~2   q_appl~3 |
         |--------------------------------|
      1. |        .          .          . |
         +--------------------------------+

    Comment


    • #3
      Actually, I think its cleaner to loop like this:

      Code:
      foreach var of varlist answer_value*{
          local newname = subinstr("`var'", "answer_value", "", 1)
          rename `var' `newname'
      }

      Comment


      • #4
        Sorry, but it looks like you can actually do this in one line.

        Code:
        rename answer_value* *

        Comment


        • #5
          Daniel - that's it!
          It looked like it was one line; no foreach loop needed.
          Right, the wildcard represents all of it with just one asterisk.
          Thanks so much.

          Comment

          Working...
          X