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.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.