3

This might be a rather simple question but I am new to SAS and am clueless even after researching on this in Google.

I have a macro variable as -

%let list = 12AUG2013 13AUG2013 15AUG2013 16AUG2014 09SEPT2014;

I need to get the following things -

a) Total words in list: In R this would be length(list). But in SAS, length counts each character. COUNTW does not work. Anyway I can do this?

b) Finding the ith word: If I need the 3rd element in this list, I would say list[3] in R. How can I do that in SAS?

c) Finding the position of an element: Suppose I need to know which position 16AUG2014 is at in the list variable, how can I get it?

Thanks for all the help!

Joe
  • 62,789
  • 6
  • 49
  • 67
RHelp
  • 815
  • 2
  • 8
  • 23
  • 2
    Any particular reason you're trying to do these things with a macro variable? If you're coming over from R, please note that macro variables are _not_ equivalent to an R `list`. You usually would not work with macro variables that contain data per se; data should always be stored in datasets (equivalent to R's data frame). Unless you're using SAS/IML, there are no vectors, lists, or matrices, only data frames. You should typically put your data in a dataset and work with it there. Macro variables are just text - they are not intended to hold data like you're trying to do. – Joe May 08 '14 at 11:28
  • 3
    In general, if you are a SAS newbie, don't try to learn the macro language first. Learn the datastep language first; that is 99% of what you will need to know to use SAS properly. Add the macro language on much later. It's too easy to learn very bad habits by trying to learn macros too early - macros shouldn't be used for the majority of what you do. – Joe May 08 '14 at 11:30

2 Answers2

6

As you're asking about macro variables, it's a little different to using SAS data-step functions. Your questions provide a useful example of how they differ. Some data-step functions have macro function equivalents %SCAN, %SUBSTR etc. Others will require the use of %SYSFUNC, which allows most SAS datastep functions to be converted into macro functions.

So, referring to your example:

%let list = 12AUG2013 13AUG2013 15AUG2013 16AUG2014 09SEPT2014;

%let list_numwords = %sysfunc(countw(&list)); /* This example shows the use of SYSFUNC */
%let list_word3 = %scan(&list,3); /* These examples show the use of SCAN and INDEX, inbuilt macro functions*/
%let list_pos16AUG2014 = %index(&list,16AUG2014);

The code creates new macro variables that store the answers to your questions a,b and c* respectively.

* If you require the word number of 16AUG2014 (i.e. 4), then this is a little more difficult as I don't think there's a string function for this in SAS. It would involve using a combination of COUNT and %SUBSTR.

mjsqu
  • 5,151
  • 1
  • 17
  • 21
5

The Code for position in list is

%let list_pos=%sysfunc(countw(%substr(&list,1,%index(&list,16AUG2014)+1)));  

Cheers

Michael Kersten
  • 427
  • 2
  • 11