Search code examples
sasconcatenation

concatenate leading spaces in SAS


I want to indent Male and Female. current F_SEX this is my data:

data T_SEX
retain SEX _7_ug_kg_day _9_ug_kg_day _12_ug_kg_day Total;
set T_SEX;
keep SEX _7_ug_kg_day _9_ug_kg_day _12_ug_kg_day Total;
by descending SEX;
if _9_ug_kg_day=" " then _9_ug_kg_day="0";
rename SEX=CHARA;
run;

data labelSEX;
length CHARA $50;
CHARA="Sex n(%)";
run;
data F_SEX;
set labelSEX T_SEX; run;

I tried to put an if statement followed by ||""variable, but I couldn't figure it out. Expected output:


Characteristics   7ugkgday 9ugkgday 12ugkgday total
Sex
  male            xxx(xxx) xxx(xxx) xxx(xxx)  xxx(xxx)
  female          xxx(xxx) xxx(xxx) xxx(xxx)  xxx(xxx)

Solution

  • Is the below what you are looking for?

    1. Create sample data sets
    data labelsex;
        infile datalines delimiter='|' dsd;
        input chara :$10.;
        datalines;
    Sex n(%)||||
    ;
    
    data have;
        infile datalines delimiter='|' dsd;
        input chara :$10. _7ug_kg_day :$10. _9_ug_kg_day :$10. _12_ug_kg_day :$10. 
            Total :$10.;
        datalines;
    Male|2 (66.7%)|3 ( 100%)|7 (70.0%)|12 (75.0%)
    Female|1 (33.3%)||3 (30.0%)|4 (25.0%)
    ;
    
    1. Compress to remove unexpected blanks
    2. Replace missing character value by 0(0%)
    3. Indent using the repeat() function. Here it is 3 times a blank space.
    data t_sex;
        length chara :$20.;
        set have;
        array char $ _character_;
    
        do over char;
            char = compress(char);
            if missing(char) then
                char='0(0%)';
        end;
        
        chara = cat(repeat(' ', 3), chara);
    run;
    
    1. Rename the chara column to Characteristics
    2. Set the two data sets together
    data want;
        set labelsex t_sex;
        rename chara=Characteristics;
    run;
    

    enter image description here

    However I don't see why you would want to indent inside a SAS table. To me it looks like you want to produce some kind of report as an output. If that is the case, I would suggest to use SAS procedures that were design to do so like PROC REPORT or PROC TABULATE.


    An example using PROC REPORT

    proc report data=t_sex nowd style(report)={rules=none frame=void cellspacing=0};
        title1 'Example using PROC REPORT';
        column chara _7ug_kg_day _9_ug_kg_day _12_ug_kg_day total;
        define chara / group order descending 'Characteristics' style(column)={cellwidth=0.5 indent=10};
        define _7ug_kg_day / center display '7ugkgday';
        define _9_ug_kg_day / center display '9ugkgday ';
        define _12_ug_kg_day / center display '12ugkgday ';
        define total / center display 'Total';
        compute before / style={just=l font_weight=bold};
            line 'Sex n(%)';
        endcomp;
    run;
    

                       enter image description here