how to retain all the way

Reply
Occasional Contributor
Posts: 14

how to retain all the way

Have:

v1

some number

. (missing from 2nd row on)

.

Desire:

v1

some number

some number (from 2nd row on)

some number

Thanks.

Super User
Posts: 11,343

Re: how to retain all the way

Is this a value that only exists on the first record? If so

data want;

     set have;

     retain tempv . ;

     if _n_ = 1 then tempv=v1;

     else v1=tempv;

     drop tempv;

run;

Respected Advisor
Posts: 3,799

Re: how to retain all the way

data have;
   id = 1;
  
do j=1,2;
     
output;
     
end;
   j=
.;
  
do _n_ = 1 to 5;
     
output;
     
end;
  
stop;
  
run;
data want;
   update have(obs=0) have;
   by id;
   output;
  
run;
Super Contributor
Posts: 307

Re: how to retain all the way

This example is just for fun . . . my preference would be the data step methods suggested by either ballardw or DN . . .

/* create some fake data with a variable (v1) that only has a value for the first observation */

data have ;
drop i;
do i = 1 to 100;
  id + 1 ;
  if i=1 then v1 = 100*ranuni(i); /* only create a number for the first record */
  else v1 = .;
  output;
end;
run;

/* "retain" the value using proc sql by doing a dummy merge */

proc sql;
create table want as
select q1.id, q2.v1
from
( select 1 as dummy1, id from have ) q1
, ( select 1 as dummy2, v1 from have (obs=1) ) q2
where q1.dummy1 = q2.dummy2
order by q1.id
;
quit ;

Respected Advisor
Posts: 3,156

Re: how to retain all the way

The more, the merrier:

data have;

  do i=1 to 10;

    if i=1 then var=100;

  else var=.;

  output;

  end;

  drop i;

run;

/*set1--join*/

data want_set1;

set have;

if _n_=1 then set have(obs=1 rename=var=_var);

  var=coalesce(var,_var);

  drop _var;

run;  

/*set2--point= option*/

data want_set2;

    set have;

  if _n_=1 then i=_n_;

  set have point=i;

  run;

  /*set3--DOW*/

  data want_set3;

  do _n_=1 to nobs;

   set have nobs=nobs;

   if _n_=1 then _var=var;

   else var=_var;

   output;

  end;

  drop _var;

  run;

Haikuo

Ask a Question
Discussion stats
  • 4 replies
  • 220 views
  • 0 likes
  • 5 in conversation