Link to home
Start Free TrialLog in
Avatar of labradorchik
labradorchikFlag for United States of America

asked on

How to split records in .dat file in SAS?

How may I split records when records are used from .dat file in SAS?

I have allrecords.dat file and I am trying to split this file into two separate files (records1.dat and records2.dat) with the following criteria:

write records with variable Var1(1:1)=1 to records1.dat (if first number in Var1 is 1 then this record should go to records1.dat)
write records with variable Var1(1:2)=2 to records2.dat (if first number in Var1 is 2 then this record should go to records2.dat)

Note: allrecords.dat file has about 20 different variables but I only would like to use Var1 for splitting purposes. I still need to keep all other variables with all data.

I have started with the below code:
data data1 data2;
  infile "allrecords";
   input @1 Var1 $char20. @22 Var2;
    if Var1='1*' then data1;
    if Var1='2*' then data2;
run;
  
data _null_;
   set data1;
     file records1;
       put @1   Var1 $char20.
             @22 Var2 $char.;
run;

data _null_;
   set data2; 
     file records2;
       put @1   Var1 $char20.
             @22 Var2 $char.;
run;

Open in new window


Any examples, comments or suggestions would be greatly appreciated!
Avatar of theartfuldazzler
theartfuldazzler
Flag of South Africa image

Hi

Use the OUTPUT statement:

data data1 data2;
  infile "allrecords";
   input @1 Var1 $char20. @22 Var2;
    if substr(Var1,1,1)='1' then OUTPUT data1;
    if Substr(Var1,1,1)='2' then OUTPUT data2;
run;
Avatar of labradorchik

ASKER

Thank you very much theartfuldazzler!

Should I still use the code below to put all data from data1 and data2 datasets to records1.dat and records2.dat? Is this the most efficient way?

data _null_;
   set data1;
     file records1;
       put @1   Var1 $char20.
             @22 Var2 $char.;
run;

data _null_;
   set data2; 
     file records2;
       put @1   Var1 $char20.
             @22 Var2 $char.;
run;

Open in new window

Hi

you can do it in one step:


DATA _NULL_;
  infile "allrecords";
   input @1 Var1 $char20. @22 Var2;

  IF SUBSTR(Var1,1,1) = '1'  then File "h:\xxx\test1.txt";
   else IF SUBSTR(Var1,1,1) = '2' THEN File "h:\xxx\test2.txt";

   PUT _ALL_;
RUN;
ASKER CERTIFIED SOLUTION
Avatar of theartfuldazzler
theartfuldazzler
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great!! I will test it and let you know how it turned out.
Thank you, theartfuldazzler!
theartfuldazzler, your second example worked fine.
This is exactly what I needed!
Thank you very much for your comments and suggestions!!