Hello,
I am looking to change values of observations that satisfy a specific condition to the values "above".
My data looks somewhat like this:
var1 var2
1 A
1 A
1 A
0 X
1 A
1 A
2 B
2 B
0 X
2 B
2 B
3 C
3 C
3 C
0 X
In this example I would like to change the value of var2 to the value of the observation above, only if the value of var1 is equal to 0.
In the example above, the result would be:
var1 var2
1 A
1 A
1 A
0 A
1 A
1 A
2 B
2 B
0 B
2 B
2 B
3 C
3 C
3 C
0 C
I hope someone can help me. Thanks alot!
data have;
input var1 var2 $;
cards;
1 A
1 A
1 A
0 X
1 A
1 A
2 B
2 B
0 X
2 B
2 B
3 C
3 C
3 C
0 X
;
data want;
set have;
k=lag(var2);
if var1=0 then var2=k;
drop k;
run;
data have;
input var1 var2 $;
cards;
1 A
1 A
1 A
0 X
1 A
1 A
2 B
2 B
0 X
2 B
2 B
3 C
3 C
3 C
0 X
;
data want;
set have;
k=lag(var2);
if var1=0 then var2=k;
drop k;
run;
data want;
set have;
prev_var2 = lag(var2);
if var1=0 then var2=prev_var2;
run;
@niki0209 wrote:
Hello,
I am looking to change values of observations that satisfy a specific condition to the values "above".
My data looks somewhat like this:var1 var2
1 A
1 A
1 A
0 X
1 A
1 A
2 B
2 B
0 X
2 B
2 B
3 C
3 C
3 C
0 X
In this example I would like to change the value of var2 to the value of the observation above, only if the value of var1 is equal to 0.
In the example above, the result would be:
var1 var2
1 A
1 A
1 A
0 A
1 A
1 A
2 B
2 B
0 B
2 B
2 B
3 C
3 C
3 C
0 C
I hope someone can help me. Thanks alot!
Hi @niki0209,
How about:
data want;
set have;
var2 = ifc(var1,var2,lag(var2));
run;
Kind regards,
Amir.
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.