Array Question

Reply
Valued Guide
Posts: 524

Array Question

Hi.

 

Can anyone tell me why I can't reference some entry in an array with the observation pointer _N_?

 

lets sat that I have some dataset and wanted to reference the entry in the array corresponding to the current observation number, what approach should I use?

 

data have;
input CharVar $ Numvar;
datalines;
A 1
B 2
C 3
;
run;

data ArrayTest;
   set have;
   
   Array SomeArray{*} Numvar;
   
   NewVar = SomeArray[_N_];
run;

The above gives me an error.

Respected Advisor
Posts: 3,776

Re: Array Question

Your ARRAY does not have enough elements. 

Valued Guide
Posts: 524

Re: Array Question

Doesn't it have three elements? One for each row in the NumVar column?

Super User
Posts: 1,253

Re: Array Question

[ Edited ]

You probably want to convert your input data into an array.

you can do it using PROC TRANSPOSE  or 

by a datastep like:

 

data have;
   retain var1 - var3;
   array varx var1-var3 ;    /* replace 3 in var3 at least to the expected number of rows or more */
input CharVar $ Numvar;
   varx(_N_) = Numvar;
    if charvar = 'Z' then output;     /* I added that row to assign end of input */

datalines;

A 1

B 2

C 3
Z .
;

run;

/* your HAVE dataset shall have just onw row with n=max(_N_) ovariables: var1 to varn */

Respected Advisor
Posts: 3,776

Re: Array Question

You are confusing observations(records) and variables.  What are you trying to do?

Super User
Posts: 1,253

Re: Array Question

what did you meant by
Array SomeArray{*} Numvar;
Grand Advisor
Posts: 10,251

Re: Array Question

Your array has exaclyt one element: Numvar. It only has the value on a current row as the SAS data step processes one row of data at a time. Let's repeat that: SAS data step only sees one row at a time. You have to do extra (some times a lot extra) work to reference values in a different row of the data and sometimes not very practical in a data step at all.

 

_N_ being in effect the row number as soon as you get to the second row the value is 2 and exceeds the size of the array and generates errors.

 

If you want to address ROW and COLUMN at the same time for all of the data then you need to move over to PROC IML to deal with matrices.

Valued Guide
Posts: 524

Re: Array Question

Thank you all Smiley Happy This makes sense.

Ask a Question
Discussion stats
  • 7 replies
  • 279 views
  • 3 likes
  • 4 in conversation