Solved
New Contributor
Posts: 4

how to choose a particular observation from a variable and assign the value to another variable?

for example, I have a dataset with 1 variable, v1. I want to choose the last observation of v1, and assign the value to a new variable v2.

in other word, I want v2 = the last observation of v1. (I can't just compute a v2 = whatever that number is because it's a series of computation)

What's the best way to do this??? Thanks!!!

Accepted Solutions
Solution
‎01-24-2013 08:40 AM
Super Contributor
Posts: 1,636

Re: how to choose a particular observation from a variable and assign the value to another variable?

data one;
input v1;
cards;
2
4
6
;

data _null_;
set one end=last;
if last then call symputx('aa',v1);
data two;
set one ;
v2=&aa;
run;

proc print;run;
Obs    v1    v2

1      2     6
2      4     6
3      6     6

All Replies
Super Contributor
Posts: 1,636

Re: how to choose a particular observation from a variable and assign the value to another variable?

example:

data one;

input v1;

cards;

2

4

6

;

data two;

set one end=last;

if last then do;

v2=v1;

output;end;

run;

proc print;run;

New Contributor
Posts: 4

Re: how to choose a particular observation from a variable and assign the value to another variable?

Thanks a lot! but I have another question... using this method, v2 only has one line of data: the last line. I need to assign this value to every line of v2; help please?

Solution
‎01-24-2013 08:40 AM
Super Contributor
Posts: 1,636

Re: how to choose a particular observation from a variable and assign the value to another variable?

data one;
input v1;
cards;
2
4
6
;

data _null_;
set one end=last;
if last then call symputx('aa',v1);
data two;
set one ;
v2=&aa;
run;

proc print;run;
Obs    v1    v2

1      2     6
2      4     6
3      6     6

Posts: 3,167

Re: how to choose a particular observation from a variable and assign the value to another variable?

Here is another alternative, one-pass plus one record:

data two;

n=nobs;

if _n_=1 then do;

set one nobs=nobs point=n;

v2=v1;

end;

set one;

retain v2;

run;

Haikuo

Super Contributor
Posts: 1,636

Hi Haikuo,

Posts: 3,167

Re: how to choose a particular observation from a variable and assign the value to another variable?

Training was good, Thanks for asking Haikuo

Not applicable
Posts: 1

Re: how to choose a particular observation from a variable and assign the value to another variable?

There is a function - lagX (field) - which returns the content of "field", but X observations before, so lag1 (v1) returns the contents of v1 in the last observation.

data one;

input v1;

cards;

2

4

6

;

data two;

set one end=last;

v2 = lag1(v1);

output;

if last then do;

v2 = v1;

v1 = .;

output;

end;

run;

proc print;run;

🔒 This topic is solved and locked.