Help using Base SAS procedures

sum over paired observations

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 5
Accepted Solution

sum over paired observations

Supposed my dataset like this:

obs x

1     5

2     6

3     9

4     8

5     6

6     7

I want to replace the first obs with the sum of the first and the second (5 replayed by 5+6=11) and the third with the sum of the third and fourth (9 replace by 9+8=17) , etc.

The resulting dataset like this:

obs x

1    11

2    6

3    17

4     8

5     13

6     7

What is the best way to do that?

Thanks!

Andrew


Accepted Solutions
Solution
‎10-07-2014 03:40 PM
Respected Advisor
Posts: 4,655

Re: sum over paired observations

Strange but simple request... Here goes:

data have;

input obs x;

datalines;

1     5

2     6

3     9

4     8

5     6

6     7

;

data want;

if not end then set have(firstobs=2 rename=x=y) end=end;

set have;

if mod(_n_, 2) = 1 then x = x+y;

keep obs x;

run;

PG

PG

View solution in original post


All Replies
Super User
Posts: 17,899

Re: sum over paired observations

Why is the second and 4th left alone?

Occasional Contributor
Posts: 5

Re: sum over paired observations

Because I want them to be there.

Super User
Posts: 17,899

Re: sum over paired observations

Well if the logic is in your head then I guess you'll have to hard code it.  Seems kinda pointless then.

Solution
‎10-07-2014 03:40 PM
Respected Advisor
Posts: 4,655

Re: sum over paired observations

Strange but simple request... Here goes:

data have;

input obs x;

datalines;

1     5

2     6

3     9

4     8

5     6

6     7

;

data want;

if not end then set have(firstobs=2 rename=x=y) end=end;

set have;

if mod(_n_, 2) = 1 then x = x+y;

keep obs x;

run;

PG

PG
Occasional Contributor
Posts: 5

Re: sum over paired observations

Straightforward and beautiful! Thanks PG!

Trusted Advisor
Posts: 1,204

Re: sum over paired observations

Another way to do it.

data want;
set have;
if mod(_n_,2) then flag+1;
run;

proc sql;
select obs,case when obs=min(obs) then sum(x) else x end as x from want
group by flag
order by obs;
quit;

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 6 replies
  • 197 views
  • 0 likes
  • 4 in conversation