user2143163
user2143163

Reputation: 3

How to read variable names and their values into a column?

get the name of variables and their values putting them into a column of another data set using sas

data 1
var1 var2 var3
1 2 3
2 3 1


data 2
no var4
1 var1= 1, var2= 2, var3=3
2 var1=2, var2= 3, var3= 1

I want data 1 to be transfered into data 2

Upvotes: 0

Views: 206

Answers (4)

data _null_
data _null_

Reputation: 9109

If you don't want to "know" the variable names you could use some file magic.

filename FT49F001 dummy; 
data new;
   set sashelp.class;
   file FT49f001;
   put (_all_)(+(-1) ', ' =) @;
   length newvar $512; 
   newvar = substr(_file_,3);
   put; 
   run; 
proc print; 
   run;

Upvotes: 1

Joe
Joe

Reputation: 63424

A bit simpler version of Keith's code, avoiding the IF:

data have;
input var1 var2 var3;
cards;
1 2 3
2 3 1
;
run;

data want;
set have;
array vars var1-var3;
array varns $ varn1-varn3;
do i = 1 to dim(vars);
  varns[i] = cats(vname(vars[i]),'=',vars[i]);
end;
var4 = catx(',', of varns[*]);
keep var4;
run;

Upvotes: 0

Longfish
Longfish

Reputation: 7602

Assuming you don't want to hard code the variable names, the below code should work.

data have;
input var1 var2 var3;
cards;
1 2 3
2 3 1
;
run;

data want;
set have;
length var4 $50;
array vars{*} var1--var3;
do i=1 to dim(vars);
if i=1 then var4=cats(vname(vars{i}),"=",vars{i});
else call cats(var4,",",vname(vars{i}),"=",vars{i});
end;
drop i;
run;

Upvotes: 1

Jonas Tundo
Jonas Tundo

Reputation: 6207

Are you looking for something like this?

DATA data1;
INPUT var1 var2 var3;
CARDS;
1 2 3 
2 3 1 
;
RUN; 

data data2;
set data1;
no=_N_;
var11= catx("= ","var1",var1);
var21= catx("= ","var2",var2);
var31= catx("= ","var3",var3);
var4= catx(", ",var11,var21,var31);
drop var1 var2 var3 var11 var21 var31 ;
run;

Upvotes: 0

Related Questions