set missing value with proc format - sas

I'm quite new to SAS and I use the proc format to attribute value to codes :
proc format;
value code_to_value
-1 = .
1 = 0.5
2 = 0.25
3 - high = 0;
run;
I then convert it to a numeric column in my dataset.
DATA foo;
SET bar;
my_var = put(my_var ,code_to_value.);
RUN;
The problem is that this code set all -1 code to ., but as a character, not as a missing value.
How can I set it to missing ?

The put() function creates a character value. Combine with input() if you want to convert back to numeric, eg:
DATA foo;
SET bar;
my_var = input(put(my_var ,code_to_value.),best.);
RUN;

Allan's input(put is a very common and legitimate construct.
Here is more information for a deeper understanding.
The value statement of Proc FORMAT creates a format. Formats always performs a 'to-text' mapping.
A numeric format maps a numeric value to a character value
A character format maps a character value to a character value
formats can be applied programmatically using the PUT, PUTC and PUTN functions
A invalue statement creates an informat.
A numeric informat maps a character value to a numeric value
A character informat maps a character value to a character value
informats can be applied programmatically using the INPUT, INPUTC and INPUTN functions
There is no format/function combination that directly maps a numeric value to a numeric value.
Using INPUT() with a numeric will perform an implicit conversion to character (not a bad thing per se) prior to using the specified numeric informat. This example shows INVALUE and INPUT.
proc format;
invalue code_to_value
-1 = .
1 = 0.5
2 = 0.25
3 - high = 0;
run;
data have;
do my_var = -2 to 4; output; end;
run;
DATA want;
SET have;
my_varx = input(my_var, code_to_value.);
RUN;
----- LOG -----
NOTE: Numeric values have been converted to character values at the places given by:

Related

SAS - Changing Existing Character Variable values to Numeric using Input

Have a variable called var1 that has two kinds of values (both as character strings). One is "ND" the other is a number out of 0-100, as a string. I want to convert "ND" to 0 and the character string to a numeric value, for example 1(character) to 1(numeric).
Here's my code attempt:
data cleaned_up(drop = exam_1);
set dataset.df(rename=(exam1=exam_1));
select (exam1);
when ('ND') do;
exam1 = 0;
end;
when ;
exam1 = input(exam_1,2.);
end;
otherwise;
end;
Clearly not working. What am I doing wrong?
A couple of problems with your code. Putting the rename statement as a dataset option against the input dataset will perform the rename before the data is read in. Therefore exam1 won't exist as it is now called exam_1. This will still be defined as a character column, so the input function won't work.
You need to keep the existing column, create a new numeric column to do the conversion, then drop the old column and rename the new one. This can be done as a dataset option against the output dataset.
The tranwrd function will replace all occurrences of 'ND' to '0', then using input with the best12 informat will read in all the data as numbers. You don't have to specify the length when reading numbers (i.e. 2. for 2 digits, 3. for 3 digits etc).
data cleaned_up (drop=exam1 rename=(exam_1=exam1));
set df;
exam_1 = input(tranwrd(exam1,'ND','0'),best12.);
run;
You are using select(exam1) while it should be select(exam_1). You can use select for this purpose, but I think simple if condition can solve this much easier:
data test;
length source $32;
do source='99', '34.5', '105', 'ND';
output;
end;
run;
data result(drop = convertedValue);
set test;
if (source eq 'ND') then do;
result = 0;
end;
else do;
convertedValue = input(source,??best.);
if not missing(convertedValue) then do;
if (0 <= round(convertedValue, 1E-12) <= 100) then do;
result = convertedValue;
end;
end;
end;
run;
input(source,??best.) tries to convert source to number and if it fails (e.g. values contains some word), it does not print an error and simply continues execution.
round(convertedValue,1E-12) is used to avoid precision error during the comparison. If you want to do it absolutely safely you have to use something like
if (0 < round(convertedValue,1E-12) < 100
or abs(round(convertedValue,1E-12)) < 1E-10
or abs(round(convertedValue-100,1E-12)) < 1E-10
)
Try to use ifc function then convert to numeric variable.
data have;
input x $3.;
_x=input(ifc(x='ND','0',x),best12.);
cards;
3
10
ND
;

Converting numeric variables to character in SAS

I have two datasets, both with same variable names. In one of the datasets two variables have character format, however in the other dataset all variables are numeric. I use the following code to convert numeric variables to character, but the numbers are changing by 490.6 -> 491.
How can I do the conversion so that the numbers wouldn't change?
data tst ;
set data (rename=(Day14=Day14_Character Day2=Day2_Character)) ;
Day14 = put(Day14_Character, 8.) ;
Day2 = put(Day2_Character, 8.) ;
drop Day14_Character Day2_Character ;
run;
Your posted code is confused. Half of it looks like code to convert from character to numeric and half looks like it is for the other direction.
To convert to character use the PUT() function. Normally you will want to left align the resulting string. You can use the -L modifier on the end of the format specification to left align the value.
So to convert numeric variables DAY14 and DAY2 to character variables of length $8 you could use code like this:
data want ;
set have (rename=(Day14=Day14_Numeric Day2=Day2_Numeric)) ;
Day14 = put(Day14_Numeric, best8.-L) ;
Day2 = put(Day2_Numeric, best8.-L) ;
drop Day14_Numeric Day2_Numeric ;
run;
Remember you use PUT statement or PUT() function with formats to convert values to text. And you use the INPUT statement or INPUT() function with informats to convert text to values.
Change the format to something like Best8.2:
data tst ;
set data (rename=(Day14=Day14_Character Day2=Day2_Character)) ;
Day14 = put(Day14_Character, best8.2) ;
Day2 = put(Day2_Character, best8.2) ;
drop Day14_Character Day2_Character ;
run;
Here is an example:
data test;
input r ;
datalines;
500.04
490.6
;
run;
data test1;
set test;
num1 = put(r, 8.2);
run;
If you do not want to specify the width and number of decimal points you can just use the BEST. informat and SAS will automatically assign the width and decimals based on the input data. However the length of the outcome variable may be large unless you specify it explicitly. This will still retain your numbers as in the original variable.

Convert mm/dd/yy to MonthName DayNumber, YearNumber in SAS

I want to be able to convert an entire column of dates this way. For example, 01/01/2017 to January 1, 2017. I realize there is a convoluted way of doing this but I am not entirely sure how i'd approach that logically. Also, does there happen to be a SAS format that does this? Thanks.
There does happen to be a format you can use. Here is a worked example using test data:
data test;
input datestring $;
datalines;
01/01/2017
;
run;
Using input converts the string value into a SAS date, and then the put function is used to create a character variable holding the representation you are looking for:
data test2;
set test;
date_as_date = input(datestring,ddmmyy10.);
date_formatted = put(date_as_date,worddate20.);
run;
The number 20 is used to describe a length that is long enough to hold the full value, using a lower number may result in truncation, e.g.
date_formatted = put(date_as_date,worddate3.);
put date_formatted=;
dateformatted=Jan
In some cases, the desired date format may NOT exist (in this case, it does 'worddate20.'), but as an example...
You could either write a function-style macro to convert a SAS date to "monname + day, year" format, e.g.
%MACRO FULLMDY(DT) ;
catx(', ',catx(' ',put(&DT,monname.),put(&DT,day.)),put(&DT,year4.))
%MEND ;
data example1 ;
dt = '26jul2017'd ;
fulldate = %FULLMDY(dt) ;
run ;
Or, you could build a custom format, covering all the dates which may exist in your data, e.g.
data alldates ;
retain fmtname 'FULLMDY' type 'N' ;
do dt = '01jan1900'd to '01jan2100'd ;
mdy = catx(', ',catx(' ',put(dt,monname.),put(dt,day.)),put(dt,year4.)) ;
output ;
end ;
rename dt = start
mdy = label ;
run ;
proc format cntlin=alldates ; run ;
data example2 ;
dt = '26jul2017'd ;
format dt fullmdy. ;
run ;

character to numeric in SAS

I'm new to sas and I have the following problem.
I have a variable that stores time but is a character, format $50. It looks like 30 min, 1.5 h, 5 h, 10 h. I need to convert it to numeric and calculate time in hours. I tried substrn function to extract numbers. but substrn(var, 1,2) gives 30, 1(instead of 1.5), 5, 10 and substrn(var, 1,3) gives 30, 1.5, .(instead of 5), 10. How to solve it?
Any help is appreciated.
Conversion from character to numeric is usually done using the input function. The second argument passes the expected informat (a rule telling SAS how to interpret the input).
You can use compress function (with the "k" option to keep rather than discard characters) to get just the numeric part of the character variable. Compress will remove certain characters from a value; the first argument passes the string for it to work on, the second argument lists the characters to remove, the third argument passes additional options (here "d" to add numerals to the list of characters to remove and "k" to invert the process. i.e. keep rather than remove the selected characters).
And, the index function can be used to identify the times when the string contains "m" for minutes. Index will return the position of the first occurrence of the the search string within the input. In the case if the input does not contain "m" it will return 0 and evaluate as FALSE in the if statement.
/* Create some input data */
data temp;
input time : $20.;
datalines;
1.5h
30min
120min
4.25hour
;
run;
data temp2;
set temp;
/* Extract only the numeric part of the string and convert to numeric */
newTime = input(compress(time, ".","dk"), best9.);
/* Check if the string contains the letter "m" and if so divide by 60 */
if index(time, "m") then newTime = newTime / 60;
run;
proc print;
run;
There's probably a way to create a custom informat that would deal with this, which I expect Joe or one of the other regulars here can advise you on. However, failing that, here's a function-based approach:
data have;
input time_raw $1-50;
cards;
30 min
1.5 h
5 h
10 h
;
run;
data want;
set have;
if index(time_raw, 'min') then do;
minutes = input(substr(time_raw,1,length(time_raw) - 4), 8.);
hours = 0;
end;
else do;
hours = input(substr(time_raw, 1, length(time_raw) - 2), 8.);
minutes = 0;
end;
format time time.;
time = hms(hours, minutes, 0);
run;

Conditionally replace column values with column name in SAS dataset

I have a SAS dataset as follow :
Key A B C D E
001 1 . 1 . 1
002 . 1 . 1 .
Other than keeping the existing varaibales, I want to replace variable value with the variable name if variable A has value 1 then new variable should have value A else blank.
Currently I am hardcoding the values, does anyone has a better solution?
The following should do the trick (the first dstep sets up the example):-
data test_data;
length key A B C D E 3;
format key z3.; ** Force leading zeroes for KEY;
key=001; A=1; B=.; C=1; D=.; E=1; output;
key=002; A=.; B=1; C=.; D=1; E=.; output;
proc sort;
by key;
run;
data results(drop = _: i);
set test_data(rename=(A=_A B=_B C=_C D=_D E=_E));
array from_vars[*] _:;
array to_vars[*] $1 A B C D E;
do i=1 to dim(from_vars);
to_vars[i] = ifc( from_vars[i], substr(vname(from_vars[i]),2), '');
end;
run;
It all looks a little awkward as we have to rename the original (assumed numeric) variables to then create same-named character variables that can hold values 'A', 'B', etc.
If your 'real' data has many more variables, the renaming can be laborious so you might find a double proc transpose more useful:-
proc transpose data = test_data out = test_data_tran;
by key;
proc transpose data = test_data_tran out = results2(drop = _:);
by key;
var _name_;
id _name_;
where col1;
run;
However, your variables will be in the wrong order on the output dataset and will be of length $8 rather than $1 which can be a waste of space. If either points are important (they rsldom are) and both can be remedied by following up with a length statement in a subsequent datastep:-
option varlenchk = nowarn;
data results2;
length A B C D E $1;
set results2;
run;
option varlenchk = warn;
This organises the variables in the right order and minimises their length. Still, you're now hard-coding your variable names which means you might as well have just stuck with the original array approach.