Placing the digits of a number into a vector


I enjoy reading about the Le Monde puzzles (and other topics!) at Christian Robert's blog. Recently he asked how to convert a number with s digits into a numerical vector where each element of the vector contains the corresponding digit (by place value). For example, if the number is 4321, then s=4 and the desired vector is {4, 3, 2, 1}.

Here's my SAS/IML solution, which converts the number to a string, and uses the SUBSTR function to grab each digit:

proc iml;
start ConvertNumberToArray(n);
   s = ceil(log10(n+1)); /** find magnitude of number **/
   c = char(n,s);  /** convert to string **/
   x = j(1,s);     /** allocate vector **/
   do i = 1 to s;
      x[i] = num(substr(c,i,1)); /** substring, as numeric **/
   return (x);
x = ConvertNumberToArray( 4321 ); /* {4 3 2 1} */

About Author

Rick Wicklin

Distinguished Researcher in Computational Statistics

Rick Wicklin, PhD, is a distinguished researcher in computational statistics at SAS and is a principal developer of PROC IML and SAS/IML Studio. His areas of expertise include computational statistics, simulation, statistical graphics, and modern methods in statistical data analysis. Rick is author of the books Statistical Programming with SAS/IML Software and Simulating Data with SAS.

1 Comment

  1. Pingback: Compute the number of digits in an integer - The DO Loop

Leave A Reply

Back to Top