Hi there,
I'm having some problems using the preserve and restore functions in a loop.
When I run the code below the code block for sex works fine - I get excel spreadsheets for both categories of sex.
However, the second block of code (for age) works for the first level(category) of age (& produces an excel spreadsheet) but when the loop goes to run for the second time I get the error "no observations r(2000);".
What am I doing wrong?
Thank you in advance!
Mel
I'm having some problems using the preserve and restore functions in a loop.
When I run the code below the code block for sex works fine - I get excel spreadsheets for both categories of sex.
However, the second block of code (for age) works for the first level(category) of age (& produces an excel spreadsheet) but when the loop goes to run for the second time I get the error "no observations r(2000);".
What am I doing wrong?
Thank you in advance!
Mel
Code:
*Sex cd "xxx" use xxx.dta, clear levelsof sex, local(levels) foreach lev of local levels{ preserve display "sex = `lev'" tabstat sleep_dur_tue_before sleep_dur_wed_before sleep_dur_thur_before sleep_dur_fri_before sleep_dur_sat_before sleep_dur_sun_after sleep_dur_mon_after sleep_dur_tue_after sleep_dur_wed_after sleep_dur_thur_after if sex == `lev', stats(mean sem) save return list matrix spring_matrix_sex_`lev' = r(StatTotal) matrix list spring_matrix_sex_`lev' svmat spring_matrix_sex_`lev' save "spring_matrix_sex_`lev'.dta", replace keep spring_matrix_sex_`lev'* drop if spring_matrix_sex_`lev'1 ==. export excel spring_matrix_sex_`lev'.xlsx, firstrow(varlabels) replace restore } *Age cd "xxx" use xxx.dta, clear levelsof age_accel_tert, local(levels) foreach lev of local levels{ preserve display "age = `lev'" tabstat sleep_dur_tue_before sleep_dur_wed_before sleep_dur_thur_before sleep_dur_fri_before sleep_dur_sat_before sleep_dur_sun_after sleep_dur_mon_after sleep_dur_tue_after sleep_dur_wed_after sleep_dur_thur_after if sex == `lev', stats(mean sem) save return list matrix spring_matrix_age_`lev' = r(StatTotal) matrix list spring_matrix_age_`lev' svmat spring_matrix_age_`lev' save "spring_matrix_age_`lev'.dta", replace keep spring_matrix_age_`lev'* drop if spring_matrix_age_`lev'1 ==. export excel spring_matrix_age_`lev'.xlsx, firstrow(varlabels) replace restore }
Comment