-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlStructures.R
More file actions
138 lines (117 loc) · 2.3 KB
/
ControlStructures.R
File metadata and controls
138 lines (117 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
######### IF ELSE
x
if( x >3 )
{
y <- 10
} else
{
y <- 0
}
y
# OR
y <- if( x > 3 ) { 10 } else { 0 }
### FOR LOOP
# 1.
for( i in 1:10)
{
print(i)
}
# 2.
x <- c( "a", "b", "c", "d" )
for( idx in 1:4 )
{
print( x[idx]) # Mere x[idx] doesn't print the value.
}
# 3. Using seq_along()
# The seq_along() function is commonly used in conjunction with
# for loops in order to generate an integer sequence based on the
# length of an object (in this case, the object x).
for( idx in seq_along(x) )
{
print( x[idx] )
}
seq_along(x) # Result: 1 2 3 4
#4. It is not necessary to use an index to be an integer always.
# Instead the index variable can take values from the vector itself.
for( letter in x )
{
print(letter)
}
# 5. For one line loops, curly braces are not necessary
for( idx in 1:4 ) print( x[idx])
########## NESTED FOR LOOP
x <- matrix( 1:6, 2, 3 )
x
nrow(x) # Returns the number of rows in matrix
seq_len(nrow(x)) # Creates an integer sequence of specified length.
for( i in seq_len( nrow( x )))
{
for( j in seq_len( ncol( x )))
{
print( x[i, j])
}
}
#### WHILE LOOPS
count <- 0
while( count < 10 )
{
print( count )
count <- count + 1
}
# While loops with multiple conditions
z <- 5
set.seed(1)
while( z >= 3 && z <= 10 )
{
coin <- rbinom( 1, 1, 0.5 )
if( coin == 1 )
{
z <- z + 1
}
else
{
z <- z - 1
}
}
print( z )
# repeat LOOPS
#repeat initiates an infinite loop from the start.
# The only way to exit a repeat loop is to call break.
########### DON'T EXECUTE THE BELOW CODE.
x0 <- 1
tol <- 1e-8
x1 <- 0
repeat
{
# x1 <- computeEstimate() # it's an imaginary function
if( abs(x1 - x0) < tol )
{
break
}
else
{
x0 <- x1
}
}
##############
# next is used to skip an iteration of a loop
for( i in 1:100 )
{
if( i <= 20 )
{
# Skip the first iterations
next
}
#### To do
}
# break is used to exit a loop immediately, regardless of what
# iteration the loop may be on.
for( i in 1:100 )
{
print( i )
if( i > 20 )
{
# Stop loop after 20 iterations
break
}
}