claire_123
claire_123

Reputation: 85

Replace string with numerical data in Stata error type mismatch r(109);

I'm attempting to reformat the following data

treatment
text-only
text-only
text-only
text-only
text-only
text-only
text+photo
text+photo
text+photo
text+photo
text+photo
text+photo
text+video
text+video

as binary data (0,1,2) I use the following code, but receive the following error. What am I doing wrong?

Thanks!

replace treatment = 0 if treatment == "text-only"
type mismatch
r(109);

Upvotes: 1

Views: 6736

Answers (2)

Ryan Wendling
Ryan Wendling

Reputation: 61

I take it you are not really looking to create a binary variable (only zeros and ones) but rather just a numeric variable.

The problem you are running into is that you want to replace strings with integers. These are two different data types, and in Stata you can't have a variable with two different data types.

You solved this problem by making the integers strings. This solves one problem, but could create others. The best way to solve your problem is to use encode

This is a simple way to preserve the original variable and create a new numeric variable based on the original string. You code would look like this:

encode treatment, gen(id_treatment)

This will give you a new variable called id_treatment that will be numeric, but will have value labels that correspond to the original strings. You will also still have the original string variables if you need them.

Upvotes: 2

claire_123
claire_123

Reputation: 85

Figured it out!

replace treatment = "0" if treatment == "text-only"

This works^

Upvotes: 0

Related Questions