thyde
thyde

Reputation: 131

Isolating unique observations and calculating the average in Stata

Currently I have a dataset that appears as follows:

 mnbr      firm       contribution
 1591      2          1
 9246      6          1
 812       6          1
 674       6          1

And so on. The idea is that mnbr is the member number of employees who work at firm # whatever. If contribution is 1 (and I have dropped all the 0s for this purpose) said employee has contributed to a certain fund.
I additionally used codebook to determine the number of unique firms that exist. The goal is to determine the average number of contributions per firm i.e. there was 1 contribution for firm 2, 3 contributions for firm 6 and so on. The problem I arrive at is accessing that the unique values number from codebook.
I read some documentation online for

inspect *varlist*
display r(N_unique)

which suggests to me that using r(N_unique) would store that value, yet unfortunately this method did not work for me. So that is part 1.

Part 2 is I'd also like to create a variable that shows the contributions in each firm i.e.

 mnbr      firm       contribution      average
 1591      2          1                 1
 9246      6          .                 2/3
 812       6          1                 2/3
 674       6          1                 2/3

to show that for firm 6, 2 out of the 3 employees contributed to this fund.
Thanks in advance for the help.

Upvotes: 0

Views: 987

Answers (1)

Roberto Ferrer
Roberto Ferrer

Reputation: 11102

To answer your comment, this works for me:

clear
set more off 

input ///
 mnbr      firm       cont
 1591      2          1
 9246      6          .
 812       6          1
 674       6          1
 end

list

// problem 1
inspect firm
display r(N_unique)

// problem 2
bysort firm: egen totc = total(cont)
by firm: gen share = totc / _N

list

You have to use r(N_unique) before running another Stata command, or it can get lost. You can also save that result to a local or scalar.

Problem 2 is also addressed.

Upvotes: 1

Related Questions