0

I have generated a string variable in the following way:

gen Category = "none"
replace Category = "Pineapple" if d == 400 | d == 800
replace Category = "Mango" if d == 300 | d == 700
replace Category = "Apple" if d == 200 | d == 600
replace Category = "Orange" if d == 100 | d == 500

sort Category 
by Category, sort: egen Total_volume = sum(volume)

sort  Category
quietly by  Category:  gen dup = cond(_N==1,0,_n)
drop if dup>1
drop dup

in the end, I hope to have a output that is sorted by Category, and appear in the order:

>     Category    Total_volume
>     Pineapple   2929
>     Mango    5454
>     Apple   1020
>     Orange   5055

However, through running the code, some of the observations were dropped so to obtain a single line for a sum of the total volume, what I so far got was in an alphabetical order.

>     Category    Total_volume
>     Apple   1020
>     Mango    5454
>     Orange   5055
>     Pineapple   2929

How could I adjust so that the output shows in the order I arranged in the current code?

2
  • 1
    Please study stackoverflow.com/help/mcve For example, the definition of d is irrelevant to this question. datex from SSC (in Stata, type ssc inst dataex) is a way of generating self-contained data examples. Commented Apr 25, 2016 at 14:19
  • Not the question but the repeated sorts are not needed here. Commented Apr 25, 2016 at 14:19

1 Answer 1

2

A string variable when sorted is necessarily in alphabetic order, or more generally the order given by the string characters used. If you map to a numeric variable, you can use value label definitions to insist on a different order. See the help for encode and label.

label def Category 1 "Pineapple" 2 "Mango" 3 "Apple" 4 "Orange" 
encode Category, gen(Numeric) label(Category)
sort Numeric 
Sign up to request clarification or add additional context in comments.

Comments

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.