Created
October 7, 2013 01:55
-
-
Save MonkmanMH/6861482 to your computer and use it in GitHub Desktop.
while() and for() loops in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PRINT THE INTEGERS 1 THROUGH 10 | |
# | |
# VERSION 1 -- using while() | |
# make the initial assignment of variable count_1 to 0 (not necessary) | |
count_1 <- 0 | |
# the while loop - conditional statement in the first parenthesis, | |
# then the repeated steps within the {} | |
while (count_1 < 10) | |
{ count_1 <- count_1 + 1 | |
print(count_1) | |
} | |
# | |
# | |
# VERSION 2 -- using for() | |
# and a vector instead of 10 iterations of the object | |
# define a vector "counter" with 10 elements | |
counter <- numeric(10) | |
# print the vector, which is populated with zeros | |
print (counter) | |
# for the first through tenth elements, assign the element the value of the position in the loop | |
for (i in 1:10) | |
counter[i] <- i | |
# print the vector | |
print (counter) | |
# | |
# | |
# ================================ | |
# If this is an assignment "Print the integers 1 through 10", then a couple of other approaches are possible | |
# | |
# VERSION 3a -- R has a sequence function! | |
# simply entering "1:10" will print the list of the integers from 1 to 10 | |
1:10 | |
# | |
# VERSION 3b - a more elaborate and flexible approach | |
seq(from=1, to=10, by=1) | |
# variant: counting backwards from zero to -20 by 2 | |
seq(from=0, to=-20, by=-2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment