- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
Posted 11-14-2021 12:37 PM
(2218 views)
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!
4 REPLIES 4
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
--
Paige Miller
Paige Miller
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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.