Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAS, create filename from dataset column

Tags:

sas

is it possible to create a filename from a value stored in a dataset column? What i'm after is something like:

/* 
   other code here, assume work.users looks like 
   user_id
   ImageData
 */

data _null_;
   set work.users;

   file_name=cat('/home/me/', trim(user_id), '.jpg');

   file file_name NOPRINT;

   put ImageData;
run;

at the moment i'm trying to do it with macros but i'm not having any luck.

like image 679
vasdee Avatar asked Jan 20 '23 08:01

vasdee


2 Answers

To do this, you'll need to create the file_name variable first, and then you can use the filevar= option in a new data step to dynamically write to the files.

So, first create file_name in work.users:

data work.users;
  length file_name $255;
  file_name=cats('/home/me',user_id,'.jpg');
run;

Then do what you're trying to do using the filevar= option:

data _null_;
  set work.users;
  file dummy filevar=file_name noprint;
  put ImageData;
run;

Note that dummy is just a placeholder when using the filevar= method.

like image 144
sasfrog Avatar answered Jan 28 '23 08:01

sasfrog


If you want to do this with macros:

data _null_;
  set work.users;
  call symput('filename', cats('/home/me/', user_id, '.jpg'));
run;

data _null_;
  set work.users;
  file "&filename." noprint;
  put imagedata;
run;

However, this assumes there is only one observation in work.users, which I'm guessing is not true. If you want to output a file for each observation, roll it into a macro:

%macro writefile(n);
%do i = 1 %to &n;

data _null_;
    i = &i;
    set users point=i;
    call symput('filename', cats('c:\temp\', user_id, '.txt'));
    stop;
run;

data _null_;
    i = &i;
    set users point=i;
    file "&filename." noprint;
    put imagedata;
    stop;
run;

%end;
%mend;

Here, the argument &n is the number of observations in your dataset. You could obtain it programmatically, but it's easier for current purposes just to pass it manually to the macro.

like image 38
Hong Ooi Avatar answered Jan 28 '23 06:01

Hong Ooi