简体   繁体   中英

Equivalent to SAS function repeat in PROC IML

I want to define a string in a PROC IML , say "aaaaa" (five "a"). In a DATA step, I would use the repeat() function, which creates a string repeating substrings, as explained in the documentation .

data _null_;
x=repeat('a',4);    /* string with five 'a' */
put x;
run;

However, in SAS/IML, the repeat() function is different : it creates a matrix repeating elements of another one (documentation here ). So if I use this function, I will get a vector with five "a" elements.

proc iml;
x=repeat('a',5);    /* 5 'a' strings */
print x;
quit;

In that example, I could obviously not bother and go directly with :

x="aaaaa";

But what if I needed a larger string (say 100 "a" for example) ? I could also create it outside of the PROC IML and import it after but there must be a more clever way to address the problem, isn't there ?

There is no need to write a loop. Use the ROWCATC function to concatenate the elements across columns:

proc iml;
N = 10;
x = rowcatc(repeat("a", 1, N));  /* repeat 'a' N times */
print x (nleng(x))[L="Length"];

A slightly harder problem is to concatenate elements and insert some sort of delimiter beteen the elements (blanks, comas, etc). That problems is discussed in the article "Convert a vector to a string."

As IML works with matrices, that is what you normally would want. To get columns instead of rows:

proc iml;
  x=repeat('a', 1, 5);   
  print x;
quit;

 x
a a a a a

You could convert the vector to string using a loop. But in that case it would make more sense to skip repeat and directly use a loop to produce a string:

proc iml;
  x="";
  do i = 1 to 5;
    x = x + 'a';
  end;
  print x;
quit;

 x
aaaaa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM