Hello
I want to ask how can I create a conditional statement that convert specific variable from char to numeric.
As you understand in some cases the variable will be numeric and then no need to transfer.
And in other cases variable will be char and then need to transfer it to numeric.
Cases1:
Data a;
input x $;
cards;
1
2
3
;
run;
case2:
Cases1:
Data a;
input x ;
cards;
1
2
3
;
run;
Data a;
input x ;
cards;
1
2
3
;
run;
data b;
length x $10.;
set a(rename=(x=_x));
x=put(_x,best.);
run;
Am sure a basic question like this you asked before?
data want; set a; if notdigit(x) then y=.; else y=input(x,best.); run;
The fast and dirty way to do it is this, no need for any conditional statements:
data b;
length x 8; /* declare X as numeric */
set a(rename=(x=_x));
x=_x;
drop _x;
run;
If the original X is character, you will get a message about conversion in the log.
Not sure what level you consider "you will get a message about conversion in the log" - this would come out as an issue for my logs. Implicit conversion should be avoid.
@Ronein wrote:
Hello
I want to ask how can I create a conditional statement that convert specific variable from char to numeric.
As you understand in some cases the variable will be numeric and then no need to transfer.
And in other cases variable will be char and then need to transfer it to numeric.
Cases1:
Data a;
input x $;
cards;
1
2
3
;
run;
case2:
Cases1:
Data a;
input x ;
cards;
1
2
3
;
run;
Short answer: you can't. A variable type is set at creation, either numeri or character. If a value is going to hold non-missing character values the variable type must be character. You can have two variables, on character one numeric and conditionally assign VALUES, but not types.
If you are attempting to fix data that was imported in an undesired variable type, or inconsistent, then fix the import/ read step to use the correct type consistently. Your "example" is very common when relying on the guessing procedure Proc Import to read data and then combine data sets and discovering that because of the contents of the files Proc Import guessed differently for some files.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.