1

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

thank you for the quick reply! it's because I have multiple gender variables and i would like to preserve the order. by any chance, do you know how to move columns left and right?
You can use the command "order". That will sort variables in the order you provide, leaving all unnamed for last. Say you have the following variable list: a b c d e, but you want "e and d" to be first, you would do "order e d" this will leave the variables as e d a b c
You can store numeric characters in strings, so that using "1" as a replacement would have been legal (but not helpful).
encode by default will create integers 1 up with value labels formed from the strings supplied. As in the question, for statistical purposes people usually prefer indicators (often called dummy variables) with values 0 and 1. You can get that with encode by defining the value labels explicitly ahead of the encode. stata-journal.com/article.html?article=dm0099 also gives a detailed discussion.
0

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

3 Comments

This isn't the best solution. Having value labels is a good idea and sometimes even essential. How is the researcher or the reader supposed to know that 1 means Female. See other replies.
you are exactly right! what I did was just that I just wrote something like label var1 "female=1". I saw your comment only after i solved the problem, but since it does seem more elegant, i will try it next time.
update: i added value labels separately from variable labels

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.