Automating repetitive tasks is one of SAS©'s great strengths, especially for processing large-scale surveys. However, passing parameters—such as labels or formats—inside a macro is a frequent source of syntax errors.
Automating repetitive tasks is one of SAS©'s great strengths, especially for processing large-scale surveys. However, passing parameters—such as labels or formats—inside a macro is a frequent source of syntax errors.
| 1 | %let Q1_label='Texte très long pour la question 1...'; |
| 2 | |
| 3 | %macro f_freq(var, var_w, var_label); |
| 4 | PROC FREQ DATA=clean_data order=freq; |
| 5 | TABLE &var / out=freqout.freq_&var; |
| 6 | FORMAT &var &var_w; |
| 7 | label &var=&var_label; /* Assigne le label */ |
| 8 | RUN; |
| 9 | %mend; |
| 10 | |
| 11 | /* L'appel qui ne fonctionne pas comme prévu */ |
| 12 | %f_freq(Q1, Q1_w., Q1_label); |
| 1 | /* Appel corrigé */ |
| 2 | %f_freq(Q1, Q1_w., &Q1_label); |
| 3 |
PROC FREQThe expert who responded raises an interesting technical point: "I think the format and the label are used for display... I don't think they affect the aggregation."
It is important to clarify this behavior in SAS©:
Formats (FORMAT): They do affect aggregation. If you apply a format that groups values (for example, transforming 1, 2, 3 into "Small"), PROC FREQ will calculate the frequency for "Small". This is essential for on-the-fly recoding.
Labels (LABEL): They do not affect the calculation, but they are crucial for metadata. The LABEL statement inside the procedure does indeed allow storing the variable's description in the output table (OUT=).
| 1 | %macro f_freq(var, var_w, var_label); |
| 2 | %put NOTE: La variable est &var; |
| 3 | %put NOTE: Le label reçu est &var_label; |
| 4 | /* ... reste du code ... */ |
| 5 | %mend; |
Writing macros requires particular rigor regarding variable scope. Always remember: if you want to pass the content of a variable defined by a %LET statement, you must use the & prefix in the call.
Los códigos y ejemplos proporcionados en WeAreCAS.eu son con fines educativos. Es imperativo no copiarlos y pegarlos ciegamente en sus entornos de producción. El mejor enfoque es comprender la lógica antes de aplicarla. Recomendamos encarecidamente probar estos scripts en un entorno de prueba (Sandbox/Dev). WeAreCAS no acepta ninguna responsabilidad por cualquier impacto o pérdida de datos en sus sistemas.