#conditional execution
x <- 2
if (x > 3) print("x<3") else print("x>4")
## [1] "x>4"
x <- 4
if (x < 3) {
print("x<3")
z <- "M"
} else {
print("x>3")
z <- "F"
}
## [1] "x>3"
z
## [1] "F"
#Iteration,loop
n <- 0
sum.so.far <- 0
while (sum.so.far <= 1000) {
n <- n + 1
sum.so.far <- sum.so.far + n
}
print(c(n, sum.so.far))
## [1] 45 1035
sum(1:45)
## [1] 1035
#Apply()
A <- matrix(1:20, 4, 5)
apply(A, 1, sum) #to every row
## [1] 45 50 55 60
apply(A, 2, sum) #to ever column
## [1] 10 26 42 58 74
#Writing a new function
my.stat <- function(x) {
m <- mean(x)
s <- sd(x)
res <- list(x = x, m = m, s = s)
par(mfrow = c(1, 2))
boxplot(x, main = "Boxplot")
hist(x, prob = T, col = "lightgray", main = "Histrogram", xlab = "data")
z <- seq(from = min(x), to = max(x), by = 0.01)
lines(z, dnorm(z, mean = 3, sd = 1), col = 2, lwd = 3, lty = 2)
}
data <- rnorm(1000, mean = 3, sd = 1)
my.stat(x = data)