Stata Code: wordscore

version 7.0

#delimit ;

program define wordscore, rclass;
    args scorename;
    quietly gen `scorename' = 0;

    tokenize $rtextnames;
    tempvar totwords;
    quietly gen `totwords' = .;
    while "`1'" ~= "" {;
	tempvar f`1';
	quietly replace `totwords' = sum(`1');
        quietly gen `f`1'' = `1' / `totwords'[_N];
	macro shift;
    };

    tempvar wordsumf;
    tokenize $rtextnames;	
    local addvf = "`f`1''";	
    quietly gen `wordsumf' = `addvf';
    macro shift;
    while "`1'" ~= "" {;
	quietly replace `wordsumf' = `wordsumf' + `f`1'';
        macro shift;
    };

    tokenize $rtextnames;
    while "`1'" ~= "" {;
	tempvar p`1';
        quietly gen `p`1'' = `f`1'' / `wordsumf';
	* list word `wordsumf' `f`1'' `p`1'' in 1/4;
	quietly replace `scorename' = `scorename' + (`p`1'' * ``1'[rscore]');
	macro shift;
    };

end;