0

I have a set of variables, the names of which have the same prefix attached to unique two-digit years:

div_unemp03
div_unemp04
.
.
.
div_unemp14

I would like to rename these variables to be as follows:

div_ue03
div_ue04
.
.
.
div_ue14

I attempted to carry this out using a foreach loop:

foreach x of var unemp*  {
    local new = substr(`x', 10, 2)
    rename `x' div_ue`new'
}

However, Stata produces an error code:

type mismatch

Any help in understanding this error and how to achieve the desired effect would be appreciated!

2 Answers 2

1

The substr function requires a string as its first argument. Additionally, your varlist syntax unemp* will not catch the variables named div_unemp##, since they do not begin with unemp (generating the "type mismatch" error). The (reproducible) example below shows both corrections.

clear
input div_unemp03 div_unemp04 div_unemp05
1 1 1
end

foreach x of varlist *unemp* {
    local new = substr("`x'", 10, 2)
    rename `x' div_ue`new'
}

Note also that substr() allows you to count from the end of the string, so substr("s", -2, 2) works.

Sign up to request clarification or add additional context in comments.

1 Comment

Note also in this case scope for using subinstr() to zap the mp.
0

You can do the same thing in one line by simply using the rename command:

clear
set obs 1

forvalues i = 3 / 6 {
    generate div_unemp0`i' = .
}

list, abbreviate(11)

     +-------------------------------------------------------+
     | div_unemp03   div_unemp04   div_unemp05   div_unemp06 |
     |-------------------------------------------------------|
  1. |           .             .             .             . |
     +-------------------------------------------------------+

rename div_unemp# div_ue#

list, abbreviate(10)

     +-------------------------------------------+
     | div_ue03   div_ue04   div_ue05   div_ue06 |
     |-------------------------------------------|
  1. |        .          .          .          . |
     +-------------------------------------------+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.