DATA Step, Macro, Functions and more

Explain do loops

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 6
Accepted Solution

Explain do loops

 

Please can someone explain in details the data steps below and what each data statement is doing.

 

thanks

 

data work.invest;

do year = 2010 to 2014;

capital + 3000;

capital + (capital * 0.10);

end;


Accepted Solutions
Solution
‎10-22-2015 06:35 AM
Super User
Super User
Posts: 7,997

Re: Explain do loops

The do loop repeats the code within the block the number of times specified by the from and to (and step if supplied).

data work.invest;

  do year = 2010 to 2014;

    capital + 3000;

    capital + (capital * 0.10);

  end;

In your instance, the loop variable year runs from 2010 to 2014 (default step 1), so 2010, 2011, 2012, 2013.

You can expand the code to look like:

year=2010

add 3000 to capital

add capital multiplied by 0.10 to capital

year=2011

add 3000 to capital

add capital multiplied by 0.10 to capital

 

...

 

So year will end up as 2014, and capital will be the end result of those adds.

View solution in original post


All Replies
Solution
‎10-22-2015 06:35 AM
Super User
Super User
Posts: 7,997

Re: Explain do loops

The do loop repeats the code within the block the number of times specified by the from and to (and step if supplied).

data work.invest;

  do year = 2010 to 2014;

    capital + 3000;

    capital + (capital * 0.10);

  end;

In your instance, the loop variable year runs from 2010 to 2014 (default step 1), so 2010, 2011, 2012, 2013.

You can expand the code to look like:

year=2010

add 3000 to capital

add capital multiplied by 0.10 to capital

year=2011

add 3000 to capital

add capital multiplied by 0.10 to capital

 

...

 

So year will end up as 2014, and capital will be the end result of those adds.

Occasional Contributor
Posts: 6

Re: Explain do loops

Thanks for your help. The explanation was very simplified and clear

Respected Advisor
Posts: 4,173

Re: Explain do loops

Is this an interview or study question?

 

 

Do you know SAS Language at all? Which bit of the code is not clear to you?

 

Here the documentation for a do-loop:

https://support.sas.com/documentation/cdl/en/lestmtsref/68024/HTML/default/viewer.htm#p1cydk5fq0u4bf...

 

Another good way to understand what's happening is to actually execute the code, look at the result and try to understand what's going on. Each "output" statement in below code will write a row to table "work.invest".

 

data work.invest;
  do year = 2010 to 2014;
    output;
    capital + 3000;
    output;
    capital + (capital * 0.10);
    output;
  end;
run;
Occasional Contributor
Posts: 6

Re: Explain do loops

Am new to programming and am not sure about a lot of the statements. Thanks for your help

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 226 views
  • 0 likes
  • 3 in conversation