-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperators_controlflow_loops.R
136 lines (97 loc) Β· 2.26 KB
/
operators_controlflow_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
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
############################# Relational Operators #############################
# Equality operator ( == )
5 == 5
# Not equal ( !=, ! + = )
5 != 6
# Greater and less than ( < > )
5 < 6
# Greater/less than / equal to ( <= >= )
5 <= 5
# These work on all values within a vector
x = c(1, 2, 3, 4, 5)
x < 4
x == 5
y = c(1, 2, 3, 4, 5)
x == y
# identical function
identical(x, y)
# all and any
all(y < 6)
any(y > 3)
############################### Logical Operators ##############################
# And operator (&)
5 == 5 & 4 == 4
# Or operator (|)
5 == 6 | 4 == 4
# Not operator (!)
!(5 == 6 | 4 == 4)
################################# Control Flow #################################
some_calc = function(x) {
if (x < 0) {
stop('Cannot use a negative number with this fuction!')
} else if (x == 0) {
stop('Cannot divide by 0.')
} else if (!is.numeric(x)) {
stop('This function only takes numbers.')
} else {
result = sqrt(x) / x
return(result)
}
}
some_calc('hello')
################################## For Loops ###################################
for (number in 1:5) {
print(number)
}
our_mean_function = function(x) {
if (!(is.numeric(x) & is.atomic(x))) {
stop('The input should be a numeric vector.')
}
total = 0
for (number in x) {
total = total + number
}
return(total / length(x))
}
mean(1:5)
our_mean_function(1:5)
################################# While Loops ##################################
x = 0
while (x < 10) {
print(x)
x = x + 1
}
################################ Break & Next ##################################
x = 0
while (TRUE) {
if (x >= 10) {
break
}
print(x)
x = x + 1
}
x = sample(1:100, 50, T)
for (i in x) {
if (i %% 2 == 0) {
print (i)
} else {
next
}
}
############################### Error Handling #################################
x <- list(1, 2, '3', 4, '5', 6, 7)
x * 2
result <- c()
for (i in x) {
result <- c(result, i * 2)
}
x <- list(1, 2, '3', 4, '5', 6, 7)
result <- c()
for (item in x) {
tryCatch(
result <- c(result, item * 2),
error = function(e) {
result <- c(result, as.numeric(item) * 2)
}
)
}