Hi all,
I have some datasets
1 ft 1 in 2ft2in 3 in 4in
And I want to convert all of them to numeric variables in inches.
13 26 3 4
Could anyone tell me how to do it, please? I'm confused because they have different units and spaces. Any hints would be helpful. Thank you in advance!
Here is what I have for now
Height = compress(Height);
if findw(Height,'ft') > 0 then do;
ft = input(scan(Height,1,"ft"),f1.);
in = input(scan(Height,2,"in"),best.);
Height = 12*ft + 1*in;
else;
Height = Height;
end;
It gives errors but I'm just wondering if this is the right way to go or if there are easier ones.
data heights;
input text $char60.;
cards;
1 ft 1 in
2ft2in
3 in
4in
;
data want;
set heights;
text=compress(text);
location_ft=find(text,'ft','i');
location_in=find(text,'in','i');
if location_in>0 then do;
inches=scan(substr(text,1,location_in-1),-1,,'dk');
inches_numeric=input(inches,2.);
end;
if location_ft>0 then do;
feet=scan(substr(text,1,location_ft-1),-1,,'dk');
feet_numeric=input(feet,2.);
end;
height=sum(inches_numeric,12*feet_numeric);
run;
You could use a regular expression to extract the numbers from the string:
data want;
set heights;
length feet inch total 8;
rx = prxparse('/((\d+)\s*ft)?\s*(\d+)\s*in/i');
if prxmatch(rx, text) then do;
feet = coalesce(input(prxposn(rx, 2, text), ?? best.), 0);
inch = input(prxposn(rx, 3, text), ?? best.);
total = sum(inch, feet * 12);
end;
else do;
put 'Failed ' _n_;
end;
drop rx;
run;
With data like this
data have;
infile cards truncover;
input measure $10.;
cards;
1 ft 1 in
2ft2in
3 in
4in
;run;
I would do it like this:
data want;
set have;
measure=upcase(measure);
if countw(measure,' ','A')=2 then
inches=input(scan(measure,1,' ','A'),4.)*12+
input(scan(measure,2,' ','A'),4.);
else if index(measure,'FT') then
inches=input(scan(measure,1,' ','A'),4.)*12;
else
inches=input(scan(measure,1,' ','A'),4.);
run;
I put in the UPCASE function in case you have data like '12Ft' or so.
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.