Parseltongue
Parseltongue

Reputation: 11707

Stata: Efficient way to replace numerical values with string values

I have code that currently looks like this:

replace fname = "JACK" if id==103
replace lname = "MARTIN" if id==103

replace fname = "MICHAEL" if id==104
replace lname = "JOHNSON" if id==104

And it goes on for multiple pages like this, replacing an ID name with a first and last name string. I was wondering if there is a more efficient way to do this en masse, perhaps by using the recode command?

Upvotes: 1

Views: 3081

Answers (3)

SOConnell
SOConnell

Reputation: 793

I will echo the other answers that suggest a merge is the best way to do this.

But if you absolutely must code the lines item-wise (again, messy) you can generate a long list ("pages") of replace commands by using MS Excel to "help" you write the code. Here is a picture of your Excel sheet with one example, showing the MS Excel formula:

        columns:
          A         B      C     D
row: 1  last      first    id   code
     2  MARTIN    JACK    103   ="replace fname=^"&B2&"^ if id=="&C2

You type that in, make sure it looks like Stata code when the formula calculates (aside from the carets), and copy the formula in column D down to the end of your list. Then copy the whole block of Stata code in column D generated by the formulas into your do-file, and do a find and replace (be careful here if you are using the caret elsewhere for mathematical uses!!) for all ^ to be replaced with ", which will end up generating proper Stata syntax.

(This is truly a brute force way of doing this, and is less dynamic in the case that there are subsequent changes to your generation list. All--apologies in advance for answering a question here advocating use of Excel :) )

Upvotes: 1

Ram
Ram

Reputation: 1193

Create an associative array of ids vs Fname,Lname

103 => JACK,MARTIN
104 => MICHAEL,JOHNSON
...

Replace id => hash{id} ( fname & lname )

The efficiency of doing this will be taken care by the programming language used

Upvotes: 0

Nick Cox
Nick Cox

Reputation: 37338

You don't explain where the strings you want to add come from, but what is generally the best technique is explained at

http://www.stata.com/support/faqs/data-management/group-characteristics-for-subsets/index.html

Upvotes: 0

Related Questions