BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
axescot78
Quartz | Level 8

I have long data and wrote code to track changes in 2 variables over time. However, the second entry for each userID is wrong. My data, code, and screenshot of results below. What is wrong with the code?

 

data fake_data;
input userID $ event_date date9. response $ code $;
format event_date date9.;
datalines;
1693 01Dec2014 Y V
1693 01Jan2015 Y V
1693 01Feb2015 Y V
1693 01Mar2015 M G
1693 01Apr2015 M G
1693 01May2015 M G
1129 01Feb2018 Y V
1129 01Mar2018 Y V
1129 01Apr2018 N R
1129 01May2018 N R
1129 01Jun2018 M R
1129 01Jul2018 M R 
1345 01Aug2016 N R
1345 01Sep2016 N R
1345 01Oct2016 N R
1345 01Nov2016 N R
1345 01Dec2016 M R
1345 01Jan2017 M G
1345 01Feb2017 Y G
1345 01Mar2017 Y G
1345 01Apr2017 Y G
1345 01May2017 Y G
;

proc sort data = fake_data out=fake_data_nodupkey nodupkey; by userID event_date; run;
data flag_vars;
set fake_data_nodupkey;
by userID event_date;
if first.userID then do;
	prev_response = response;
	prev_code = code;
	end;
else do;
	prev_response = lag(response);
	prev_code = lag(code);
	end;

response_change = 0;
if response ne prev_response then response_change = 1;

code_change = 0;
if code ne prev_code then code_change = 1;

run;

proc print data=flag_vars;
run;

results.PNG

1 ACCEPTED SOLUTION

Accepted Solutions
axescot78
Quartz | Level 8
data flag_vars;
set fake_data_nodupkey;
by userID ;

prev_response = lag(response);
prev_code = lag(code);

if first.userID then do;
	prev_response = response;
	prev_code = code;
	end;

response_change = 0;
if response ne prev_response then response_change = 1;

code_change = 0;
if code ne prev_code then code_change = 1;

 
run;

View solution in original post

1 REPLY 1
axescot78
Quartz | Level 8
data flag_vars;
set fake_data_nodupkey;
by userID ;

prev_response = lag(response);
prev_code = lag(code);

if first.userID then do;
	prev_response = response;
	prev_code = code;
	end;

response_change = 0;
if response ne prev_response then response_change = 1;

code_change = 0;
if code ne prev_code then code_change = 1;

 
run;

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
  • 1 reply
  • 155 views
  • 0 likes
  • 1 in conversation