SAS, create filename from dataset column
is it possible to create a filename from a value stored in a dataset column? What i'm after is something like:
开发者_Python百科/*
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.
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.
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.
精彩评论