Solved
New Contributor
Posts: 4

# Creating a new variable calculated from values of different lines

Dear SAS experts, In my data set (animal behavior) I would like to create a new variable:  the time interval between two events. There exists the variables 'first (starting time of  behavior)’ and 'Last (ending time of behavior)' per line (see attached table). I am interested in the time interval between 'last' in line n and 'first' in line n + 1. I really appreciate your help :-)

Accepted Solutions
Solution
‎11-27-2012 02:22 PM
PROC Star
Posts: 8,094

## Re: Creating a new variable calculated from values of different lines

Can't you just use the lag function?  e.g.:

libname art "c:\art";

data want;

format difference time8.;

set art.inter;

by datum name;

last_last=lag(last);

if first.name then call missing(last_last);

difference=first-last_last;

run;

All Replies
Solution
‎11-27-2012 02:22 PM
PROC Star
Posts: 8,094

## Re: Creating a new variable calculated from values of different lines

Can't you just use the lag function?  e.g.:

libname art "c:\art";

data want;

format difference time8.;

set art.inter;

by datum name;

last_last=lag(last);

if first.name then call missing(last_last);

difference=first-last_last;

run;

Posts: 3,162

## Re: Creating a new variable calculated from values of different lines

Echo with Art, you can also use dif(); sorry, Art, for stealing your code:

data want;

format difference time8.;

set art.inter;

by datum name;

/*  last_last=lag(last);

if first.name then call missing(last_last);*/

difference=ifn(first.name,.,dif(last));

run;

Haikuo

PROC Star
Posts: 8,094

## Re: Creating a new variable calculated from values of different lines

: I don't mind your "stealing" the code, but your solution doesn't meet the OP's requirements.  You are taking the difference between last and the previous last.  The OP wanted the difference between the current first and the previous last.

Posts: 3,162

## Re: Creating a new variable calculated from values of different lines

Oops, my bad. Now I know why you choose to use lag(). Haikuo

New Contributor
Posts: 4

## Re: Creating a new variable calculated from values of different lines

Dear Arthur, thank you very much! It is exactly what I wanted. Best regards from Germany Engel

🔒 This topic is solved and locked.