Pages

SyntaxHighlighter

Saturday, March 8, 2014

RGB Color Matrix

There is a scene in the movie Vegas Vacation where cousin Eddie says "I'll have some of the yella and don't get cheap on me". If you were to select a yellow, just how yellow is yellow, how blue is blue, etc...?

RGB (red, green, blue) is an additive color scheme that can produce 16.7 million colors. Each of the primary colors is comprised of hexidecimal (hex) values that range from 00 to FF or 256 unique values. If you take those 256 values to the 3rd power, for each of the 3 RGB color, you get 256**3 = 16,777,216. SAS identifies RGB colors with a CX prefix where CX000000 is black (no color), CXFF0000 is red, CX00FF00 is green, CX0000FF is blue and CXFFFFFF is white (all colors).

The idea for this post comes from a paper by Perry Watts, one of the foremost experts on SAS and colors. What I did was to extract and whittle down the 280 predefined SAS colors in the version 8 documentation and changed some of the grouped assignments. The goal was to create a one page matrix of the 161 colors that were retained. The below image reveals the structure of the retained colors in the CNS (color naming system) SAS data set.

The below code uses proc SQL to determine the size of the two dimensional array and to assign column names to the output data set. A DOW-loop is used to load data into the temporary two dimensional array to properly slot the colors into the correct locations. After that, the data from the temporary array is assigned to the columns and written to the output data set.

The compute block in proc report is used to define the background color using the RGB color code. The next image is the final resulting color matrix.

%macro rgbcolormatrix ;
  %local
    columnnames
    columncount
    tablecolumns
    tablerows
    i
    column
  ;
 
  proc sql noprint ;
    select       group
               , count( * )
      into       :columnnames separated by " "
               , :columncount separated by ","
      from       cns
      group by   group ;
  quit ;
 
  %let tablecolumns = &sqlobs. ;
  %let tablerows = %sysfunc( max( &columncount. ) ) ;
 
  data sascolors( keep = obs &columnnames. ) ;
    length Obs 3 ;
    array atemp[ &tablerows., &tablecolumns. ] $8 _temporary_ ;
    array akeep[ &tablecolumns. ] $8 &columnnames. ;
 
    do until( eof ) ;
      col + 1 ;
      do row = 1 by 1 until( last.group ) ;
        set cns end = eof ;
          by group ;
        atemp[ row, col ] = rgb ;
      end ;
    end ;
 
    do row = 1 to &tablerows. ;
      do col = 1 to &tablecolumns. ;
        akeep[ col ] = atemp[ row, col ] ;
      end ;
      obs + 1 ;
      output ;
    end ;
  run ;
 
  ods listing close ;
  ods pdf
    file      = "%sysfunc( pathname( work ) )\rgbcolormatrix.pdf"
    notoc
    author    = "Tom Bellmer"
    title     = "RGB Color Matrix" ;
 
    options nodate nonumber ;
    title ;
 
    proc report
      data = sascolors
      style( header ) = [ background = cx4d7ebf foreground = cx000000 ]
      nowd
    ;
 
      columns obs ( 'RGB Colors' &columnnames. ) ;
      define obs / center ;
 
      %do i = 1 %to &tablecolumns. ;
        %let column = %scan( &columnnames., &i. ) ;
        compute &column. ;
          if not missing( &column. ) then do ;
            if substr( &column., 3, 1 )
              in ( '0', '1', '2', '3', '4', '5', '6' ,'7' )
              and &column. not in ( 'CX00FF00', 'CX00FFFF' ) then
              colorval = cat( 'style={foreground=white background='
                , &column., ' font_size = 8pt}' ) ;
            else
              colorval = cat( 'style={foreground=black background='
                , &column., ' font_size = 8pt}' ) ;
 
            call define( _col_, 'style', colorval ) ;
          end ;
        endcomp ;
      %end ;
 
    run;
  ods pdf close;
  ods listing;
%mend ;

Saturday, February 22, 2014

Alternating colored rows and columns

The below code shows how to use SAS's proc report to display alternating colored rows and to have the header and 1st column have matching colors. This is all accomplished using ODS style attributes.

ods html body = "x.html" style=sasweb ;
  proc report 
    data = sashelp.class
    nowd 
    style( header ) = [ background = red ]
  ;
    where age > 14 ;

    column name sex age height weight ;

    compute name ;
      count + 1 ;
      if mod( count, 2 ) then 
           call define( _row_, 'style', 'style=[background = cxd9d9d9]' ) ;
      else call define( _row_, 'style', 'style=[background = cxe9f3ff]' ) ;

      call define( _col_, 'style', 'style = [ foreground = white background = red]' ) ;
    endcomp ;     
  run ;

ods html close ;

Friday, January 31, 2014

First Friday of a full week

I had a recent request to determine the first Friday of the first full week of the month. The NWKDOM() function makes this very easy to accomplish since it returns the nth occurance of a weekday for the supplied month and year.

NWKDOM(n, weekday, month, year)

  • n - numeric week of the month
  • weekday - day of the week with 1 = Sunday
  • month - numeric month value
  • year - numeric year value
data _null_ ;
  mo   = 1 ;
  year = 2014 ;
  if nwkdom( 1, 1, mo, year ) > nwkdom( 1, 6, mo, year ) 
    then firstfullfriday = nwkdom( 2, 6, mo, year ) ;
  else firstfullfriday = nwkdom( 1, 6, mo, year ) ;
  put firstfullfriday worddate. ;
run ;

January 10, 2014

Monday, January 27, 2014

Validate SAS

Sometimes the exact same code on the same OS but on a different machine will not produced the same result, or more likely will produce an error on one machine but not another. If that happens, consider using the SASIQ.EXE utility to verify that SAS is properly installed.

The below macro assumes the sastest folder is below the install folder (!SASROOT). When you run the macro a new subfolder named validate_yyyymmdd.000 will be created. In my case, a 349 page PDF file named sasiq.pdf was created. The first page (see below) is a quick summary followed by details showing expected vs actual checksum values for critical SAS files.

%macro validatesas( path = c:\temp\ ) ;
  systask command "'%sysget(sasroot)\sastest\sasiq.exe' -outputpath &path." wait ;
%mend ;

For more information, see this link: http://support.sas.com/rnd/migration/planning/validation/sasiq.html

Saturday, January 25, 2014

Macro IN Operator

Starting in SAS 9.2 you can use the macro IN operator via the MINOPERATOR option and associated MINDELIMITER option. The MINOPERATOR is OFF (NOMINDELIMITER) by default and can be used as a global option (e.g. options minoperator ; ) or the more flexible and preferred macro option (after the slash [ / ] on the macro definition) as shown in the below example. This is especially critical for stored and compiled macros as the options are reflected at compilation time.

The default delimiter is a BLANK so if you want to a comma, specify it using the MINDELIMITER= option.

%macro test( state ) / minoperator mindelimiter=',' ;
  %if %upcase( &state. ) in( CO, KS, MO, IL ) %then %do ;
    %put its in there ;
  %end ;
  %else %put not found ;
%mend ;

%test( KS )
%test( NY )

119  %test( KS )
its in there
120  %test( NY )
not found

If you want to use this as a negative version [ NOT IN() ] you need to place the NOT around the entire expression, not just next to the IN operator as follows:

%macro test( state ) / minoperator mindelimiter=',' ;
  %if not( %upcase( &state. ) in( CO, KS, MO, IL ) ) %then %do ;
    %put its in there ;
  %end ;
  %else %put not found ;
%mend ;

%test( ks )
%test( ny )

8    %test( ks )
not found
9    %test( ny )
its in there

Monday, January 13, 2014

Using Wingdings in PROC REPORT

The idea for this post came from the book "PROC REPORT by Example" - Techniques for Building Professional Reports Using SAS by Lisa Fine.

To get a listing of Wingdings (or other available fonts), click on Windows | All Programs | Accessories | System Tools | Character Map. In the below case, Wingdings was chosen as the font and the bolded down arrow is associated with hex code EA.

<

An example using the up (E9) and down (EA) wingding fonts with proc report can be seen below.

proc format ;
  value arrow
    low -< 14 = "ea"x
    14 - high = "e9"x ;

  value color 
    low -< 14 = red
    14 - high = green ;
run ;

ods listing close ;
ods html file = "c:\temp\wingdings.html" ;
  proc report data = sashelp.class( obs = 5 ) nowd ;
    column name age direction ;
    define name / display ;
    define age  / analysis  ;
    define direction /  
       computed 
       format = arrow. 
       style( column ) = [ font_face = wingdings just = c ] ;

    compute direction ;
      direction = age.sum ;
      call define( "direction", "style", "style = [ foreground = color. ]" ) ;
    endcomp ;
  run ;
ods html close ;
ods listing ;

Wednesday, November 20, 2013

The Need for Speed - %SCAN loop

Have you ever had to write a macro to parse words in a string using the %SCAN function and wondered what is the best, most efficient technique? The below code compares the time it takes to do this using three different techniques.

In my test, I repeated the 26 letters of the alphabet 10 times so that a total of 260 scans are performed as a benchmark. Review the below code and then see the bar chart of the average time it took after five attempts of each macro. It is clearly best to use the COUNTW() function once to detemine the number of times to loop.

data _null_ ;
  length string $1028 ;
  do i = 1 to 10 ;
    do j = 65 to 90 ;
      string = catx( " ", string, byte( j ) ) ;
     end ;
  end ;
  call symput( 'macvar', string ) ;
run ;

%let starttime = %sysfunc( datetime() ) ;
%macro good ;
  %local i retval ;
  %let i = 1 ;
  %do %while( %scan( &macvar., &i. ) ne ) ;
    %let i = %eval( &i + 1 ) ;
    %let retval = %scan( &macvar., &i. ) ;
  %end ;
%mend ;
%put %sysevalf( %sysfunc(datetime()) - &starttime. ) ;

%let starttime = %sysfunc( datetime() ) ;
%macro better ;
  %local i retval ;
  %let i = 1 ;
  %let retval = %scan( &macvar., &i. ) ;
  %do %while( &retval. ne ) ;
    %let i = %eval( &i. + 1 ) ;
    %let retval = %scan( &macvar., &i. ) ;
  %end ;
%mend ;
%better
%put %sysevalf( %sysfunc(datetime()) - &starttime. ) ;

%let starttime = %sysfunc( datetime() ) ;
%macro best ;
  %local i retval ;
  %let totalwords = %sysfunc( countw( &macvar ) ) ;
  %do i = 1 %to &totalwords ;
    %let retval = %scan( &macvar., &i. ) ;
  %end ;
%mend ;
%best
%put %sysevalf( %sysfunc(datetime()) - &starttime. ) ;

Click graph for a sharper image.