Control Flow
Control Flow
If
x <- 5
if(x > 0){
print("Positive number")
}
## [1] "Positive number"
x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}
## [1] "Negative number"
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
## [1] "Zero"
# Create vector quantiy
x <- 10
# Create multiple condition statement
if (x <20) {
print('Good')
} else if (x > 20 &x <= 30) {
print('Average')
} else {
print('Bad!')
}
## [1] "Good"
Product | Discount |
---|---|
A | 3 |
B | 15 |
C | 30 |
Product <- 'A'
price <- 100
if (Product =='A'){
cat('3% discount is applied.','The discounted price is',price-price *0.03)
} else if (Product =='B'){
cat('15% discount is applied.','The discounted price is',price-price *0.15)
} else {
cat('30% discount is applied.','The discounted price is',price-price *0.3)
}
## 3% discount is applied. The discounted price is 97
For
for(i in 1:5)
print(i^2)
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
for(i in 1:5)
print(1:i)
## [1] 1
## [1] 1 2
## [1] 1 2 3
## [1] 1 2 3 4
## [1] 1 2 3 4 5
n <- 6 # sample size
n_iter <- 10^5 # number of iterations of loop (equivalent to p)
means <- numeric(n_iter)
sds <- numeric(n_iter)
sems <- numeric(n_iter)
for(i in 1:n_iter){
y <- rnorm(n) # mean=0 and sd=1 are default so not necessary to specify
means[i] <- mean(y)
sds[i] <- sd(y)
sems[i] <- sd(y)/sqrt(n)
}
sd(means)
## [1] 0.4069374
mean(sems)
## [1] 0.3885883
While
i <- 1
N <- c(1:20)
numsum = 0
while (numsum<100) {
numsum = numsum + N[i]
i = i + 1
print(numsum)
}
## [1] 1
## [1] 3
## [1] 6
## [1] 10
## [1] 15
## [1] 21
## [1] 28
## [1] 36
## [1] 45
## [1] 55
## [1] 66
## [1] 78
## [1] 91
## [1] 105