Converting character to numeric

Reply
New Contributor
Posts: 2

Converting character to numeric

Hello folks,

 

I have a problem that I have no been able to solve.  Basically, I want to recode the character R as the numeric missing value 999 but keep getting the error "invalid numeric data" error.  Thanks for any help!

 

*Recode missing values;
DATA autonomy; SET autonomy;

	ARRAY old(16) $16     aauto1-aauto8 mauto1-mauto8;
	ARRAY recode(16)  aauto1-aauto8 mauto1-mauto8;

		DO i = 1 to 16 BY 1;
	    	IF old{i}='R' THEN recode{i}=999; 
	END;
	DROP i;
RUN;

 

PROC Star
Posts: 1,833

Re: Converting character to numeric

[ Edited ]
 

 

DATA autonomy; SET autonomy;

	ARRAY old(16) $16     aauto1-aauto8 mauto1-mauto8;
	

		DO i = 1 to 16 BY 1;
	    	IF old{i}='R' THEN old{i}='999'; 
	END;
	DROP i;
RUN;

 

Super User
Posts: 10,278

Re: Converting character to numeric

Your code will work if your variables are of type character:

data autonomy;
input (aauto1-aauto8 mauto1-mauto8) ($);
cards;
1 2 3 4 R 6 7 8 1 2 3 4 R 6 7 8
;
run;

DATA autonomy; SET autonomy;

	ARRAY old(16) $16     aauto1-aauto8 mauto1-mauto8;
	ARRAY recode(16)  aauto1-aauto8 mauto1-mauto8;

		DO i = 1 to 16 BY 1;
	    	IF old{i}='R' THEN recode{i}=999; 
	END;
	DROP i;
RUN;

But if your variables are in fact numeric, and just have a format applied to them that displays the character R, you get the invalid numeric data error:

proc format;
value myform
  999 = 'R'
  other=[best10.]
;
run;

data autonomy;
input aauto1-aauto8 mauto1-mauto8;
format aauto1-aauto8 mauto1-mauto8 myform.;
cards;
1 2 3 4 999 6 7 8 1 2 3 4 999 6 7 8
;
run;

proc print data=autonomy noobs;
run;

DATA autonomy; SET autonomy;

	ARRAY old(16) $16     aauto1-aauto8 mauto1-mauto8;
	ARRAY recode(16)  aauto1-aauto8 mauto1-mauto8;

		DO i = 1 to 16 BY 1;
	    	IF old{i}='R' THEN recode{i}=999; 
	END;
	DROP i;
RUN;

See the output from the proc print:

aauto1  aauto2  aauto3  aauto4  aauto5  aauto6  aauto7  aauto8  mauto1  mauto2  mauto3  mauto4  mauto5  mauto6  mauto7  mauto8

  1       2       3       4       R       6       7       8       1       2       3       4       R       6       7       8   
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
New Contributor
Posts: 2

Re: Converting character to numeric

Posted in reply to KurtBremser

Thanks all.  After trying everyone's suggestion, the problem still persists.  I know a crude way of solving it, so I'm going to go with that for now.

Ask a Question
Discussion stats
  • 3 replies
  • 88 views
  • 1 like
  • 3 in conversation