Solved
Contributor
Posts: 27

# Choosing a variable from the next row

Suppose you've got a dataset with variables var1 and var2. When var1 is equal to a certain value, you want to take the value of var2 in the next row down.

How do you do that?

Marco

Accepted Solutions
Solution
‎09-24-2013 07:51 AM
Posts: 3,852

## Re: Choosing a variable from the next row

data next;
set sashelp.class end=eof;
if not eof then set sashelp.class(firstobs=2 keep=weight rename=(weight=_weight));
if sex eq 'F' and not eof then weight=_weight;
run;

All Replies
Super Contributor
Posts: 339

## Re: Choosing a variable from the next row

Hi,

Here's an example way to do it:

data _null_;

set sashelp.class(rename=(height=var1 weight=var2));

if get_var2 then

do;

call symputx('var2_value',var2);

stop;

end;

if var1=57.3 then

get_var2+1;

run;

%put var2_value=&var2_value;

regards,

Amir.

Contributor
Posts: 27

## Re: Choosing a variable from the next row

Amir:

it successfully creates a dataset, but how do I then get the value for var2 for a particular one of var1? The dataset just has an extra column 'var2' which is zero everywhere except for that particular value of var1.

Super Contributor
Posts: 339

## Re: Choosing a variable from the next row

Hi,

Do you want to create:

A) A data set with one row showing the var1 value and the next var2 value

B) A macro variable holding the value

C) Something else, please specify with an example.

I saw a post from you that has since been deleted saying that SAS did not recognise the macro variable reference, in that case try replacing:

call symputx('var2_value',var2);

with

call symputx('var2_value',var2,'G');

to make the scope of the variable global, if, for example, it is being created in a macro function, and is being referenced outside of that macro function.

Regards,

Amir.

Solution
‎09-24-2013 07:51 AM
Posts: 3,852

## Re: Choosing a variable from the next row

data next;
set sashelp.class end=eof;
if not eof then set sashelp.class(firstobs=2 keep=weight rename=(weight=_weight));
if sex eq 'F' and not eof then weight=_weight;
run;
Regular Contributor
Posts: 151

## Re: Choosing a variable from the next row

data ds_view / view=ds_view;

merge ds1

ds1 (firstobs=2 keep=var2 rename=(var2=nextvar2));

run;

data want (drop=nextvar2);

set ds_view;

if var1=1 then var1=nextvar2;

run;

🔒 This topic is solved and locked.