Aaron Wolf
Aaron Wolf

Reputation: 357

Extract value label in command [stata]

I am trying to create a new string variable that combines the string of a real number (an ID) with a name. The name is a numeric variable with a value label.

Example data can be found below:

* Input Data
clear
input long num id
1 689347
2 972623
end
label values num num
label def num 1 "Label A" 2 "Label B"

 +------------------+
 |     num       id |
 |------------------|
 | Label A   689347 |
 | Label B   972623 |
 +------------------+

What I would like to do is create a string of the type 689347 - Label A. This is very easy to do by simply using decode on num, then writing a new string as follows:

tempvar numstr
decode num, gen(`numstr')
gen label = string(id) + " - " + `numstr'

 +-------------------------------------+
 |     num       id              label |
 |-------------------------------------|
 | Label A   689347   689347 - Label A |
 | Label B   972623   972623 - Label B |
 +-------------------------------------+

This is already pretty easy, but is there a way to do this in one line, without the decode command?

For example something like:

gen label = string(if) + " " + string(num)

The problem with this is, of course, that this will just give a string of the real number value (1 and 2) that num takes on.

In this post you can see how to reference the value label in an if command.

My question is:

Is there a way to tell Stata to create a string and pull the value label instead of the value?

Upvotes: 1

Views: 5767

Answers (2)

Richard Herron
Richard Herron

Reputation: 10102

The best I can do is two lines.

decode num, generate(label)
replace label = string(id) + " - " + label

Upvotes: 1

user8682794
user8682794

Reputation:

If you do not want to use decode, then this does the trick:

generate label = ""

forvalues i = 1 / 2 {
    replace label = string(id) + " - " + "`: label num `i''" in `i'
}

Upvotes: 1

Related Questions