简体   繁体   中英

How can I make the first row of a SAS dataset the variable names?

I have an already imported dataset where the first row contains the variable names. I know that typically when importing a dataset you use getnames = yes. However, if the data is already imported how can I make the first row the variable names using a data step?

Data looks like:

         A         B         C 
1      Name 1   Name 2     Name 3
2        2        4          66
3        3        5          6

Since reading the names as data probably made all of your variables character you can try just transposing the data twice to fix it. That will work well for small datasets.

So the first transpose will place the current name into the _NAME_ variable and convert each row into a column. The second proc transpose can drop the original name and use the first row (new COL1 variable) as the names.

proc transpose data=have out=wide ;
 var _all_;
run;

proc transpose data=wide(drop=_name_ rename=(col1=_name_)) out=want(drop=_name_ _label_);
   var col:;
   id _name_;
run;

The problem with the already imported data is that all the numeric data was likely placed in a character variables because the 'first row' of data seen by the import process contained some character data, and drove the inference for automatic column construction.

Regardless, you will need to construct renaming pairs old-name = new-name for each variables that has to be renamed. The new-name being in row 1 makes it possible to transpose that row to arrange those name parts as data. SQL with :into and separated by can populate a macro variable for use in a proc datasets step that performs the column renaming without rewriting the entire data set. Finally, a DATA step with modify can remove a row in place, again, without rewriting the entire data set.

filename sandbox temp;

data _null_;
  file sandbox;
  put 'A,B,C';
  put 'Name 1, Name 2, Name 3';
  put '2,4,66';
  put '3,5,6';
run;

proc import datafile=sandbox dbms=csv replace out=work.oops;
run;

proc transpose data=oops(obs=1) out=renames;
var _all_;
run;           

proc sql noprint;
  select cats(_name_,"=",compress(col1,,"KN"))
  into :renames separated by ' '
  from renames;

%put NOTE: &=renames;

proc datasets nolist lib=work;
  modify oops;
  rename &renames;
run;

data oops;
  modify oops;
  remove;
  stop;
run;

%let syslast=oops;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM