BookmarkSubscribeRSS Feed
lalaktgrau
Fluorite | Level 6

Hi all,

 

I have data that has 1 observation per person per minute. 

Variables ID Time (DATETIME16.) Moving (binary 0 and 1)Sleep (binary 0 and 1)

 

I want to summarize how many instances of sleep there are (the number of times sleep =0 in between sleep =1). However, if there is more than one change from 1 to 0 in a ten minute period, I only want it to count as once. Is there a way to loop through the previous ten minutes at each observation?

 

data WORK.CLASS;
infile datalines truncover;
input Name:$8. moving sleep datetime;
informat datetime datetime20.;
format datetime datetime20.;
datalines;
Alfred 0 0 04MAR14:23:55:00
Alfred 0 1 04MAR14:23:56:00
Alfred 1 0 04MAR14:23:57:00
Alfred 1 1 04MAR14:23:58:00
Alfred 1 0 04MAR14:23:59:00
Alfred 1 1 05MAR14:00:00:00
Alfred 1 1 05MAR14:00:01:00
Alfred 1 1 05MAR14:00:02:00
Alfred 1 1 05MAR14:00:03:00
Alfred 1 1 05MAR14:00:04:00
mary 1 1 04MAR14:23:55:00
mary 1 0 04MAR14:23:56:00
mary 1 1 04MAR14:23:57:00
mary 0 0 04MAR14:23:58:00
mary 0 0 04MAR14:23:59:00
mary 1 0 05MAR14:00:00:00
mary 1 1 05MAR14:00:01:00
mary 1 1 05MAR14:00:02:00
mary 1 1 05MAR14:00:03:00
mary 1 1 05MAR14:00:04:00
run;

  

2 REPLIES 2
Reeza
Super User
You can use lag1(dt) ... lag10(dt) to reference previous variables. Or you can use a temporary array approach https://gist.github.com/statgeek/27e23c015eae7953eff2
s_lassen
Meteorite | Level 14

You do not need to look backwards. Just store the last time the person fell asleep (assuming your data is sorted by name and datetime, as shown):

data want;
  count=0;
  do until(last.name);
    set class;
    by name sleep notsorted;
    if first.sleep and sleep and fell_asleep<intnx('minute',datetime,-10) then do;
      fell_asleep=datetime;
      count=count+1;
      end;
    end;
  format fell_asleep datetime20.;
run;

You may want to drop the fell_asleep variable, I did not in order to check it.

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
  • 2 replies
  • 922 views
  • 0 likes
  • 3 in conversation