Encoding

Encoding

by Sharad Wadhwani -
Number of replies: 2

Hi all,

I am trying to encode the alcohol variable to a categorical variable but I cannot figure out how to assign order to the new variable (i.e. ensure that None = 0). Would someone be willing to help me?


Thanks,

Sharad

In reply to Sharad Wadhwani

Re: Encoding

by Michael Sadighian -
This was hard for me too. My solution required two steps: first I encoded the alcohol variable to convert it from string to numeric (I called it "alcohol_n"....which, as you pointed out, didn't yield the numeric order that the questions asks for with 0=none). The second step I took was to generate a new variable (called "alcohol_numeric") and assign new labels (i.e. 0=none), and then I used the "replace if" command to use these new labels (e.g. "replace alcohol_numeric = 0 if alcohol_n == 3").

Hope this helps. And if anyone sees problems or issues with my approach, I'd appreciate feedback.

-Michael
In reply to Sharad Wadhwani

Re: Encoding

by Michelle-linh Nguyen -
Hi Sharad,

I first converted "alcohol" from a string variable to a new ordered categorical variable (i.e. alcohol_num) using the "encode" function. I then used the "recode" function on the new categorical variable to assign the appropriate numbers to 1, 0, and missing. You can use the "codebook" function to see what numbers you need to assign to 1, 0 and missing and plug them into the range indications (i.e. the "min/2" below would assign the "1" to any value of 2 or less, AKA in the range of minimum to 2).

recode original variable (min/2 = 1 "True") (3/3 = 0 "False")(4/max = .), gen(new variable name)

That seemed to work for me. I think Michael's way would work as well and probably better if the numbers of the original variable weren't ordered in a way that you could use the ranges. Hope this is helpful.