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-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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