cc88
cc88

Reputation: 178

Transforming a variable from string to numeric

I'm trying to convert a binary variable from a string (e.g. "Male" or "Female") into binary (0 and 1). I tried with the following:

replace q1=1 if q1=="Female"

but I get the following error: type mismatch. What is the issue and how can I fix it?

Please note that I do not want to create a new variable, but only to conditionally replace values in the existing one.

Upvotes: 1

Views: 1259

Answers (2)

cc88
cc88

Reputation: 178

I figured out the solution: turn it into a number of a type string and use the destring command.

replace q1="1" if q1=="Female"
destring q1, replace

Upvotes: 0

Fcold
Fcold

Reputation: 156

You can't do that, unfortunately. You HAVE to create a new variable. The problem is that q1 is currently of string type. So it cannot store numerical data as such.

Why don't you just create a new variable, and "drop" the old one?

encode q1, gen(q1b)
drop q1
ren q1b q1

Upvotes: 2

Related Questions