summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
plot(cars)
# For Loop
for (i in 1:5){
print(paste("Iteration", i))
}
## [1] "Iteration 1"
## [1] "Iteration 2"
## [1] "Iteration 3"
## [1] "Iteration 4"
## [1] "Iteration 5"
#While Loop
x <- 1
while (x <=5) {
print(x^2)
x<- x + 1
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
summarize <- function(x){
m <- mean(x)
s <- sd(x)
return(c(mean=m, sd=s))
}
summarize(c(5, 10, 15, 20))
## mean sd
## 12.500000 6.454972
Loops are great tools to use when coding as they can optimize repetitive instructions or keep things running. While loops and for loops are two very useful kinds.
mexp <- function(x){
b = 0
for (i in 1:x){
b = b + i^2
}
print(b)
}
mexp(9)
## [1] 285
mexp(1)
## [1] 1
mexp(4)
## [1] 30