import issue with SAS due to large columns headers - csv

I have many csv files with many variable column headers , up to 2000 variable column headers for some files.
I'm trying to do an import but at one point , the headers are truncated in a 'random' manner and the rest of the data are ignored therefore not imported. I'm putting random between quotes because it may not be random although I don't know the reason if it is not random. But let me give you more insight .
The headers are truncated randomly , some after the 977th variables , some others after the 1401th variable.
The headers are like this BAL_RT,ET-CAP,EXT_EA16,IVOL-NSA,AT;BAL_RT,ET-CAP,EXT_EA16,IVOL-NSA,AT;BAL_RT,ET-CAP,EXT_EA16,IVOL-NSA,AT
This the part of the import log
642130 VAR1439
642131 VAR1440
642132 VAR1441
642133 VAR1442 $
642134 VAR1443 $
642135 VAR1444 $
As you can see , some headers are seen as numeric although all the headers are alphanumeric as they are blending a mixture of character and numeric.
Please find my code for the import below
%macro lec ;
options macrogen symbolgen;
%let nfic=37 ;
%do i=1 %to &nfic ;
PROC IMPORT OUT= fic&i
DATAFILE= "C:\cygwin\home\appEuro\pot\fic&i..csv"
DBMS=DLM REPLACE;
DELIMITER='3B'x;
guessingrows=500 ;
GETNAMES=no;
DATAROW=1;
RUN;
data dico&i ; set fic&i (drop=var1) ;
if _n_ eq 1 ;
index=0 ;
array v var2-var1000 ;
do over v ;
if v ne "" then index=index+1 ;
end ;
run ;
data dico&i ; set dico&i ;
call symput("nvar&i",trim(left(index))) ;
run ;
%put &&nvar&i ;
%end ;
%mend ;
%lec ;
The code is doing an import and also creating a dictionnary with the headers as some of them are long (e.g more than 34 characters)
I'm not sure if these elements are related however, I would welcome any insights you will be able to give me.
Best.

You need to not use PROC IMPORT, as I mentioned in a previous comment. You need to construct your dictionary from a data step read in, because if you have 2000 columns times 34 or more long variable names, you will have more than 32767 record length.
An approach like this is necessary.
data headers;
infile "whatever" dlm=';' lrecl=99999 truncover; *or perhaps longer even, if that is needed - look at log;
length name $50; *or longer if 50 is not your real absolute maximum;
do until length(_infile_)=0;
input name $ #;
output;
end;
stop; *only want to read the first line!;
run;
Now you have your variable names. Now, you can read the file in with GETNAMES=NO; in proc import (you'll have to discard the first line), and then you can use that dictionary to generate rename statements (you will have lots of VARxxxx, but in a predictable order).

Related

SAS CSV export has an unwanted leading comma in each row

I'm new to SAS and am struggling to export data to CSV. My code successfully exports a file but it has a leading comma on each non-header row that creates a misalignment.
I feel like I am missing something obvious and could really use some help. Thank you!
data _null_;
file "/export.csv";
set "/table" (keep= field1 field2 'field 3'n);
if _n_ = 1 then
do; /* write header row */
put "field1"
','
"field2"
','
"field3";
end;
do;
put (_all_) (',');
end;
run;
My output ends up looking like this...
field1,field2,field3,
,x ,y ,z
,a ,b ,c
,d ,e ,f...
or
Field1
Field2
Field3
x
y
z
a
b
c
d
e
f
Use proc export instead. It'll save you a lot of time and effort compared to coding a manual export of .csv.
proc export
data = table(keep=field1 field2 field3)
file = '/export.csv'
dbms = csv
replace;
run;
Since you seem to already know the variable names (since you have hard coded the header line) then just modify the PUT statement to not insert the extra comma.
put field1 (field2 'field 3'n) (',');
But really you should just tell SAS you are writing a delimited file by using the DSD option.
/* write header row */
data _null_;
file "/export.csv";
put "field1,field2,field 3";
run;
/* Add the actual data */
data _null_;
file "/export.csv" dsd mod ;
set table;
put field1 field2 'field 3'n ;
run;
If you don't actually know the variable names in advance then just ask SAS to generate them for you.
/* write header row */
proc transpose data=table(obs=0) out=names;
var _all_;
run;
data _null_;
file "/export.csv" dsd;
set names;
put _name_ #;
run;
/* Add the actual data */
data _null_;
file "/export.csv" dsd mod ;
set table ;
put (_all_) (+0);
run;
A general version using my second favorite CALL routine.
data _null_;
file log ls=256 dsd; /*change LOG to your file*/
set sashelp.heart;
if _n_ eq 1 then link names;
put (_all_)(:);
return;
names:
length _name_ $32;
do while(1);
call vnext(_name_);
if _name_ eq '_name_' then leave;
put _name_ #;
end;
put;
return;
run;
In the interim, I had Magoo'd may way into a method that works, too, but these are all good answers.
I used the dsd file statement option.
data _null_;
file "/export.csv"; dsd delimiter=",";
set "/table" (keep= field1 field2 'field 3'n);
if _n_ = 1 then
do; /* write header row */
put "field1"
','
"field2"
','
"field3";
end;
do;
put (_all_) (+0);
end;
run;
One more option, which does work if renaming the columns.
ODS CSV
LABELS option to print labels instead of variable names which allows for renaming. Also supports changing/applying formats while exporting.
ods csv file='/home/fkhurshed/demo.csv';
proc print data=sashelp.class label noobs;
label age= 'Age (years)' sex = 'Sex' weight = 'Weight (lbs)' height = 'Height (inches)';
run;
ods csv close;

CSV data got truncated by SAS

I'm using SAS University Edition 9.4
This is my CSV data.
,MGAAAAAAAA,3,A0000B 2F1
11111,ハアン12222234222B56122,4,AA 0000
,テストデータ,5,AACHY 2410F1
,テストデタテストテ,5,AACHYF2
This is my infile statement.
data wk01;
infile '/folders/myfolders/data/test_csv.txt'
dsd delimiter=','
lrecl=1000 missover firstobs=1;
input firstcol :$ secondcol :$ thirdcol :$ therest :$;
run ;
I expected my result like this.
But after executing SAS, What I got is as below (the yellow highlight indicates which row/column have its data being truncated by SAS)
For example, the first row's second column is MGAAAAAAAA but SAS's outut is MGAAAAAA
Could you please point out what am I missing here? Thanks alot.
The values of your variables are longer than the 8 bytes you are allowing for them. The UTF-8 characters can use up to 4 bytes each. Looks like some of them are getting truncated in the middle, so you get an invalid UTF-8 code.
Just define longer lengths for your variables instead of letting SAS use the default length of 8. In general it is best to explicitly define your variables with a LENGTH or ATTRIB statement. Instead of forcing SAS to guess how to define them based on how you first use them in other statements like INPUT, FORMAT, INFORMAT or assignment.
data wk01;
infile '/folders/myfolders/data/test_csv.txt' dsd dlm=',' truncover ;
length firstcol $8 secondcol $30 thirdcol $30 therest $100;
input firstcol secondcol thirdcol therest;
run ;
I think what you have is a mixed encoding problem. What's essentially happening is that after the first 5 characters which are in ASCII, it changes to UTF8. The commas are getting mixed up in this soup and your standard delimiter gets a bit confused here. You need some manual coding like this to deal with it I think :
data wk01;
infile "test.csv" lrecl=1000 truncover firstobs=1;
input text $utf8x70.;
firstcomma = findc(text,',', 1);
secondcomma = findc(text,',', firstcomma + 1);
thirdcomma = findc(text,',', secondcomma + 1);
fourthcomma = findc(text,',', thirdcomma + 1);
length firstcol $5;
length secondcol $30;
length thirdcol $1;
length fourthcol $30;
firstcol= substr(text,1, firstcomma - 1);
secondcol = substr(text, firstcomma + 1, (secondcomma -firstcomma-1 ));
thirdcol = substr(text, secondcomma + 1, (thirdcomma - secondcomma - 1));
fourthcol = substr(text, thirdcomma + 1);
run;
Probably there is a cleaner way to do it, but this is the quick and dirty method I could come up at 2 AM :)

How to handle an apostrophe in an href in SAS

I have a SAS program that sends out an email using HTML, but one of the folders I am trying to reference as a link contains an apostrophe:
%let body1 = %nrquote(
<ul>
<li><a href='\\server\Studies\Alzheimer's\Documents'>Alzheimer's Documents</a>
</ul>
) ;
This macro variable will be used in the following macro:
%macro sas_email(to=, subject=, body1=, body2=, body3=) ;
options
emailsys=smtp
emailhost=("smtp.gmail.com" port=465) ;
filename alert email to=(&to.)
subject="&subject."
content_type="text/html"
debug ;
data _null_ ;
file alert ;
put "&body1." ;
%if %length(&body2.) > 0 %then %do ;
put "&body2." ;
%end ;
%if %length(&body3.) > 0 %then %do ;
put "&body3." ;
%end ;
run ;
%mend sas_email ;
As you can imagine, the apostrophe in \Alzheimer's causes issues. Using double quotes instead of single gives me the error:
ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric
operand is required. The condition was: %length(&body1.) > 0
HTML doesn't care if you use double quotes or single quotes. So your generated HTML tag could look like this:
<a href="\\server\Studies\Alzheimer's\Documents">
If you want to add single quotes into a string enclosed in single quotes then encode it.
<a href='\\server\Studies\Alzheimer%27s\Documents'>
Since you are going to use the macro variable in a data step try just using %BQUOTE() to add macro quoting when creating the value. This should let you create a string that would look to SAS like unbalanced quotes.
%let body1 = %bquote(
<ul>
<li>Alzheimer's Documents
</ul>
) ;
%let body2=;
%let body3=;
Then when using it avoid trying to expand the macro variable by using symget() function to pull the value of the macro variable into an actual variable that you can then write using the PUT statement.
data _null_;
file alert ;
length str $32767;
do i=1 to 3;
str=symget(cats('body',i));
put str ;
end;
run;

SAS - Reading Raw/Delimited file

I'm having an issue reading a CSV file into a SAS dataset without bringing each field with my import. I don't want every field imported, but that's the only way I can seem to get this to work. The issue is I cannot get SAS to read my data correctly, even if it's reading the columns correctly... I think part of the issue is that I have data above my actual column headers that I don't want to read in.
My data is laid out like so
somevalue somevalue somevalue...
var1 var2 var3 var4
abc abc abc abc
Where I want to exclude somevalue, only read in select var's and their corresponding data.
Below is a sample file where I've scrambled all the values in my fields. I only want to keep COLUMN H(8), AT(46) and BE(57)
Here's some code I've tried so far...
This was SAS generated from a PROC IMPORT. My PROC IMPORT worked fine to read in every field value, so I just deleted the fields that I didn't want, but I don't get the output I expect. The values corresponding to the fields does not match.
A) PROC IMPORT
DATAFILE="C:\Users\dip1\Desktop\TU_&YYMM._FIN.csv"
OUT=TU_&YYMM._FIN
DBMS=csv REPLACE;
GETNAMES=NO;
DATAROW=3;
RUN;
generated this in the SAS log (I cut out the other fields I didn't want)
B) DATA TU_&YYMM._FIN_TEST;
infile 'C:\Users\fip1\Desktop\TU_1701_FIN.csv' delimiter = ',' DSD lrecl=32767
firstobs=3 ;
informat VAR8 16. ;
informat VAR46 $1. ;
informat VAR57 $22. ;
format VAR8 16. ;
format VAR46 $1. ;
format VAR57 $22. ;
input
VAR8
VAR46 $
VAR57 $;
run;
I've also tried this below... I believe I'm just missing something..
C) DATA TU_TEST;
INFILE "C:\Users\fip1\Desktop\TU_&yymm._fin.csv" DLM = "," TRUNCOVER FIRSTOBS = 3;
LABEL ACCOUNT_NUMBER = "ACCOUNT NUMBER";
LENGTH ACCOUNT_NUMBER $16.
E $1.
REJECTSUBCATEGORY $22.;
INPUT ACCOUNT_NUMBER
E
REJECTSUBCATEGORY;
RUN;
As well as trying to have SAS point to the columns I want to read in, modifying the above to:
D) DATA TU_TEST;
INFILE "C:\Users\fip1\Desktop\TU_&yymm._fin.csv" DLM = "," TRUNCOVER FIRSTOBS = 3;
LABEL ACCOUNT_NUMBER = "ACCOUNT NUMBER";
LENGTH ACCOUNT_NUMBER $16.
E $1.
REJECTSUBCATEGORY $22.;
INPUT #8 ACCOUNT_NUMBER
#46 E
#57 REJECTSUBCATEGORY;
RUN;
None of which work. Again, I can do this successfully if I bring in all of the fields with either A) or B), given that B) includes all the fields, but I can't get C) or D) to work, and I want to keep the code to a minimum if I can. I'm sure I'm missing something, but I've never had time to tinker with it so I've just been doing it the "long" way..
Here's a snippet of what the data looks like
A(1) B(2) C(3) D(4) E(5) F(6) G(7)
ABCDEFGHIJ ABCDMCARD 202020 4578917 12345674 457894A (blank)
CRA INTERNALID SUBCODE RKEY SEGT FNM FILEDATE
CREDITBUR 2ABH123 AB2CHE123 A28O5176688 J2 Name 8974561
With a delimited file you need to read all of the fields (or at least all of the fields up to the last one you want to keep) even if you do not want to keep all of those fields. For the ones you want to skip you can just read them into a dummy variable that you drop. Or even one of the variables you want to keep that you will overwrite by reading from a later column.
Also don't model your DATA step after the code generated by PROC IMPORT. You can make much cleaner code yourself. For example there is no need for any FORMAT or INFORMAT statements for the three variables you listed. Although if VAR8 really needs 16 digits you might want to attach a format to it so that SAS doesn't use BEST12. format.
data tu_&yymm._fin_test;
infile 'C:\Users\fip1\Desktop\TU_1701_FIN.csv'
dlm=',' dsd lrecl=32767 truncover firstobs=3
;
length var8 8 var46 $1 var57 $22 ;
length dummy $1 ;
input 7*dummy var8 37*dummy var46 10*dummy var57 ;
drop dummy ;
format var8 16. ;
run;
You can replace the VARxx variable names with more meaningful ones if you want (or add a RENAME statement). Using the position numbers here just makes it clearer in this code that the INPUT statement is reading the 57 columns from the input data.

Reading multiple csv files into SAS datasets

I have the following csv files and I need to read them into SAS datasets.
Also, I need to assign column names.
In addition, I need the column to be numberic but some columns have both number and character values.
folder aa: abc1.csv, abc2.csv, abc3.csv,......
folder bb: abc1.csv, abc2.csv, abc3.csv,......
folder cc: abc1.csv, abc2.csv, abc3.csv,......
You could do it in following way also.
Keep all your files in one folder.
Name all of them in a csv file with only one column.
Import the file (csv) with file names into SAS.
Create a macro to keep their name with "into" clause.
proc sql;
select name_list into :name separated by '*' from work.name;
%let count2 = &sqlobs;
quit;
Create a macro like below.
%macro yy;
%do i = 1 %to &count2;
%let j = %scan(&name,&i,*);
proc import out = &j datafile="folderwhereallcsvfilesarekept\&j..csv"
dbms=csv replace;
getnames = yes;
run;
%end;
%mend;
This isn't a complete answer, but it will get you started. You'll have to add an outer loop to go through the different directories you want to get files from.
/*List the files in a directory for use in a data step. This is written for Windows. Other operating systems will be slightly different. */
filename fnames pipe 'dir c:\temp\* /b';
/* Create a data set with one observation for each file name */
data fnames;
infile fnames pad missover;
input #1 filename $255.;
n=_n_;
run;
/* Store the number of files in a macro variable "num" */
proc sql noprint; select count(filename) into :num; quit;
/* Create a macro to iterate over the filenames, read them in, and append to a data set. */
%macro doit;
%do i=1 %to &num;
proc sql noprint;
select filename into :filename from fnames where n=&i;
quit;
data ds;
infile &filename;
input ...list of variable names...;
...other statements...;
run;
proc append data=ds base=final; run;
%end;
%mend;
%doit;