반복문 (Loop)

The while loop

while(condition) {
   syntax 1
   syntax 2
   .
   .
}
x <- 0
while(x < 1000) {
  x <- x + 179
}
print(x)

## [1] 1074
x <- 0
while(x < 1000) {
  x <- x + 179
  print(x)
}

## [1] 179
## [1] 358
## [1] 537
## [1] 716
## [1] 895
## [1] 1074

The for loop

for (var in vector) {
   syntax 1
   syntax 2
   .
   .
}
for(value in 1:10) {
  answer <- 137 * value
  print(answer)
}

## [1] 137
## [1] 274
## [1] 411
## [1] 548
## [1] 685
## [1] 822
## [1] 959
## [1] 1096
## [1] 1233
## [1] 1370

words <- c("it", "was", "the", "dirty", "end", "of", "winter")

for(this_word in words) {
  n_letters <- nchar(this_word)
  block_word <- toupper(this_word)
  cat(block_word, "has", n_letters, "letters\n")
}

## IT has 2 letters
## WAS has 3 letters
## THE has 3 letters
## DIRTY has 5 letters
## END has 3 letters
## OF has 2 letters
## WINTER has 6 letters

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.