-
Notifications
You must be signed in to change notification settings - Fork 4
/
While Loops.R
79 lines (54 loc) · 1.06 KB
/
While Loops.R
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
# While Loops
x <- 0
while(x<10){
print(paste0('x is: ',x))
x <- x+1
if(x==10){
print("X is now equal to 10! Break loop!")
break
print("Woo I printed too!")
}
}
# 5
x <- 0
while(x<10){
print(paste0('x is: ',x))
x <- x+1
if(x==5){
print("X is now equal to 5! Break loop!")
break
}
}
### For Loops
v <- c(1,2,3)
for(variable in v){
print(variable)
}
v<- c(1,2,3,4,5)
for(temp.var in v){
# Execute some code
# for every temp.var in v
print(temp.var)
}
v <- c(1,2,3,4,5)
for(temp.var in v){
result <- temp.var + 1
print('The temp.var plus 1 is equal to:')
print(result)
}
my.list <- list(c(1,2,3), mtcars,12)
for(item in my.list){
print(item)
}
mat <- matrix(1:25,nrow=5)
for(num in mat){
print(num)
}
mat <- matrix(1:25,nrow = 5)
for(row in 1:nrow(mat)) {
for(col in 1:ncol(mat)) {
print(paste('The selected row is:' , row))
print(paste('The element at row:' , row, 'and col: ', 'is',mat[row,col]))
}
}
mat