Search code examples
sasdo-loops

SAS: Do loop summing rows from 1 to value specified by a column


I am working with an insurance coverage data set that contains coverage status 1 (yes) or 0 (no) for day 1 to 365. I need to create a variable is the sum of 1s but only until a certain day, which again is specified by another variable, num days. In the data set below, I want to create sum of days until the position specified by "NumDays". Therefore, the value of sum for A would be 4, B - 2, C - 2, D-4 & E-1. Any ideas how I can accomplish this? Thanks!

ID  Day2    Day3    Day4    Day5    Day6    NumDays Sum
A   1       1       1       0        1      5        ?
B   1       0       1       1        1      3        ?
C   1       1       1       1        1      2        ?
D   1       1       1       1        1      4        ?
E   1       1       1       1        1      1        ?

Solution

  • This is pretty straight forward. Create an array of all the days, then loop through the first NumDays of them adding them up.

    data want;
    set have;
    array d[*] day:;
    
    do i=1 to NumDays;
        if i <= dim(d) then
            sum = sum(sum,d[i]);
    end;
    
    drop i;
    run;