I have a wide dataset (could transpose to long, then be re-transposed if necessary) that has various outcomes at 15 time points. If missing, it will have "NA." I want to impute the first missing "NA" right after an observation. See example:
HAVE:
id | time1 | time2 | time3 | time4 | time5 |
A | 1 | NA | 2 | NA | NA |
B | 2 | 3 | NA | 3 | NA |
C | 2 | NA | NA | NA | 4 |
D | 1 | 2 | 2 | NA | NA |
WANT:
id | time1 | time2 | time3 | time4 | time5 |
A | 1 | 1 | 2 | 2 | NA |
B | 2 | 3 | 3 | 3 | 3 |
C | 2 | 2 | NA | NA | 4 |
D | 1 | 2 | 2 | 2 | NA |
Any help would be greatly appreciated!
Just work from right to left.
data have;
input id $ (time1-time5) (:$2.);
cards;
A 1 NA 2 NA NA
B 2 3 NA 3 NA
C 2 NA NA NA 4
D 1 2 2 NA NA
;
data want;
set have;
array t time1-time5;
do i=dim(t) to 2 by -1;
if t[i]='NA' then t[i]=t[i-1];
end;
drop i;
run;
Result
Although I do not understand why you would want those NA strings in your TIME variables when the other values look like numbers. If instead of that constant text you set the values MISSING then you could use MISSING() function instead of the equality operator in the IF condition.
if missing(T[i]) then ...
Just work from right to left.
data have;
input id $ (time1-time5) (:$2.);
cards;
A 1 NA 2 NA NA
B 2 3 NA 3 NA
C 2 NA NA NA 4
D 1 2 2 NA NA
;
data want;
set have;
array t time1-time5;
do i=dim(t) to 2 by -1;
if t[i]='NA' then t[i]=t[i-1];
end;
drop i;
run;
Result
Although I do not understand why you would want those NA strings in your TIME variables when the other values look like numbers. If instead of that constant text you set the values MISSING then you could use MISSING() function instead of the equality operator in the IF condition.
if missing(T[i]) then ...
Oh, simpler than I thought! Thanks!
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.