Code is:
****
DATAstring;
inputstring $10.;
DATALINES;
123nj76543
892NY10203
876pA83745
;
RUN;
****
How could I create a numeric variable called x that contains the first two digits of the string? How could I create a character variable called state that contains the fourth and fifth characters (uppercase)?
data DATAstring;
length x 8.;
input inputstring $10.;
x = substr(inputstring,1,2);
state = upcase(substr(inputstring,4,2));
DATALINES;
123nj76543
892NY10203
876pA83745
;
Do like this
DATA string;
input string $10.;
DATALINES;
123nj76543
892NY10203
876pA83745
;
RUN;
data want;
set string;
var1=input(substr(string, 1, 2), best.);
var2=upcase(substr(string, 4, 2));
run;
data DATAstring;
length x 8.;
input inputstring $10.;
x = substr(inputstring,1,2);
state = upcase(substr(inputstring,4,2));
DATALINES;
123nj76543
892NY10203
876pA83745
;
Thanks. How do you differentiate between it being a character versus a numeric variable?
See my answer above. I use the input function.
the length x 8. makes x numeric.
Ohh ok, I understand now. Thanks guys!
did you question and needs get resolved?
Thanks is nice but the communities doesn't see that your needs have been fulfilled without you selecting a solution.
Please help the community by selecting and approving one of the replies.
Good to know. I've accepted your solution VDD.
Note that using the code provided by @VDD will cause a long entry like:
NOTE: Character values have been converted to numeric values at the places given by: (Line):(Column).
which is not an error but sometimes indicates something odd has happened to your data or the code could use some cleaning.
That is why @PeterClemmensen used an INPUT to do the explicit conversion from character to numeric.
With perl regular expression you could also achieve the same as below
DATA string;
input string $10.;
x=prxchange('s/(^\d{1,2})(\d\w*)/$1/i',-1,strip(string));
state=prxchange('s/(\d?)//i',-1,upcase(strip(string)));
DATALINES;
123nj76543
892NY10203
876pA83745
;
RUN;
So bored today
DATA string;
input string $10.;
DATALINES;
123nj76543
892NY10203
876pA83745
;
RUN;
data want;
set string;
x=peekclong(addrlong(string),2);
state=upcase(compress(string,,'kai'));
run;
data want;
set string;
x=peekclong(addrlong(string),2);
state=upcase(compress(string,,'d'));
run;
data want;
input x 1-2 @4 state $upcase2.;
cards;
123nj76543
892NY10203
876pA83745
;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.
Ready to level-up your skills? Choose your own adventure.