BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
niki0209
Obsidian | Level 7

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!

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20


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;

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20


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;

Reeza
Super User
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!




Amir
PROC Star

Hi @niki0209,

 

How about:

 

data want;
   set have;
   var2 = ifc(var1,var2,lag(var2));
run;

 

 

Kind regards,

Amir.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 813 views
  • 7 likes
  • 4 in conversation