Statistical programming, matrix languages, and more

Common elements in two vectors

Reply
Occasional Contributor
Posts: 5

Common elements in two vectors

Hi,

I have a question in regard to finding the common elements in two vectors.

I have a column vector of tickers for a stock index. I have a loop over time which does some calculations at each day.

At each day inside the time loop, I have around 40 tickers, which are repeating again and again through time.

However, in some days new stocks may introduce to the index so the column vector of tickers at day t may have one of two tickers more than the column vector of tickers at day t-1.

For example, as it can be seen in the following table, at day t, NOP enters into the index for the first time. To observe these new stocks, I want to introduce a new variable as NEW which gives me zero for each common ticker and one for the new tickers which enter the index for the first time. So, how to define variable NEW in SAS/IML environment?

Your advice is appreciated.

DAY (T-1)
DAY (T)NEW
AXAAXA

0

AIAAIA0
BCDBCD0
FEJFEJ0
JUDJUD0
KIDKID0
LODLOD0
MINMIN0
OOPNOP1
QREOOP0
TREQRE0
WTFTRE0
XDEWTF0
ZSWXDE0

ZSW0
New Contributor
Posts: 3

Re: Common elements in two vectors

One solution:

data stocks;
input old $4. new $4.;
cards;
AXA AXA 0
AIA AIA 0
BCD BCD 0
FEJ FEJ 0
JUD JUD 0
KID KID 0
LOD LOD 0
MIN MIN 0
OOP NOP 1
QRE OOP 0
TRE QRE 0
WTF TRE 0
XDE WTF 0
ZSW XDE 0
    ZSW 0
;
quit;

/* ~~~~~~~~~~~~~~~~~~~~~ IML Code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

proc iml;


use stocks;
read all;

Valid_Rows = nrow( old[loc(old ^= '')] );
Valid_Old = old[loc(old ^= '')];

Mesh = repeat(new,1,valid_rows);

old_reshape = repeat(valid_old,1,nrow(mesh))`;


New_ID = (old_reshape = mesh)[,+] = 0;

print new New_ID;

quit;

SAS Super FREQ
Posts: 3,234

Re: Common elements in two vectors

I suggest using the ELEMENT function in SAS/IML 9.3.

To use Ajay's data:

/* b = elements of NEW that are elements of OLD */

b = element(new, old);

New_ID = ^b; /* change 0 <--> 1 */

print new New_ID;

If you don't have SAS 9.3, I can suggest another way.

Occasional Contributor
Posts: 5

Common elements in two vectors

Thanks,

Yes please, I am using SAS 9.2.

For further clarification, I have column vectors DAY(T) and DAY(T-1) and want to produce the column NEW by having a loop over DAYs columns.

SAS Super FREQ
Posts: 3,234

Common elements in two vectors

Here's a SAS/IML module that duplicates the functionality of the ELEMENT function that was introduced in SAS/IML 9.3:

   start elementMod(x, y);

      if ncol(x)=0 then return(_NULL_);

      b = j(nrow(x), ncol(x), 0);

      if ncol(y)=0 then return(b);

     

      u = xsect(x, y);

      if ncol(u)=0 then return(b);

     

      do i = 1 to ncol(u);

         b = bor(b, (x=u));

      end;

      return (b);

   finish;

New_ID2 = ^elementMod(new, old);

Post a Question
Discussion Stats
  • 4 replies
  • 542 views
  • 2 likes
  • 3 in conversation