본문 바로가기
Stata

[stata] 반복적 업무를 단순하게 - foreach와 forvalue 사용하기 (프로그래밍)

2017. 1. 11.

 

규칙적으로 증가하는 숫자 등에는 forvalue

불규칙한 숫자나 단어엔 foreach를 사용.

 

1. 먼저 forvalue 사용법

 

forvalues = {

... `' ...

}

 

은 반복하는 곳에 들어갈 대명사 같은 것

sequence인데 다음과 같은 식으로 사용

        - min/max to indicate a sequence of numbers from min to max in steps of one, for example 1/3 yields 1, 2 and 3, or

        - first(step)last which yields a sequence from first to last in steps of size step. For example 15(5)50 yields 15,20,25,30,35,40,45 and 50.

참조 : http://data.princeton.edu/stata/programming.html

 

예제는 아래

forvalues bot = 20(5)45 {

local top = `bot' + 4

gen age`bot'to`top' = age >= `bot' & age <= `top'

}

This will create dummy variables age20to24 to age45to49.

 

 

2. foreach

사용법

foreach in {

... `' ...

}

 

은 반복하는 곳에 들어갈 대명사 같은 것

: a-list-of-things

 

예제

foreach animal in cats and dogs {

display "`animal'"

}

 

This loop will print "cats", "and", and "dogs",

댓글