itzy
itzy

Reputation: 11755

Populate SAS variable based on content of another variable

I have a variable, textvar, that looks like this:

type=1&name=bob
type=2&name=sue

I want to create a new table that looks like this:

type  name
1     bob
2     sue

My approach is to use scan to split the variables on & so for the first observation I have

var1      var2
type=1    name=bob

So now I can use scan again to split on =:

vname = scan(var1, 1, '=');
value = scan(var1, 2, '=');

But how can I now assign value to the variable named vname?

Upvotes: 1

Views: 690

Answers (3)

Longfish
Longfish

Reputation: 7602

Obviously you haven't included your real data, but can't you just hard code some of the values if the format of the raw data is the same in each row? My code converts the "=" and "&" to "," to make the scan function easier to use.

data want (keep=type name);
set test;
_newvar=translate(testvar,",,","&=");
    type=input(scan(_newvar,2),best12.);
    length name $20;
    name=scan(_newvar,4);
run;

Upvotes: 0

Joe
Joe

Reputation: 63424

PROC TRANPSOSE is the quickest way. You need an ID variable (dummy or real).

data test;
informat testvar $50.;
input testvar $;
datalines;
type=1&name=bob
type=2&name=sue
;;;;
run;

data test_vert;
set test;
id+1;
length scanner $20 vname vvalue $20;
scanner=scan(testvar,1,"&");
do _t=2 by 1 until (scanner=' ');   
    vname=scan(scanner,1,"=");
    vvalue=scan(scanner,2,"=");
    output;
    scanner=scan(testvar,_t,"&");
end;
run;

proc transpose data=test_vert out=test_T;
by id;
id vname;
var vvalue;
run;

Upvotes: 3

goodwind89
goodwind89

Reputation: 21

Does this help? Dynamic variable names in SAS

I think I have some code to address this, but left it at my workplace.

Upvotes: 0

Related Questions