April 13, 2018
print(paste("The year is", 2016))
## [1] "The year is 2016"
print(paste("The year is", 2017))
## [1] "The year is 2017"
print(paste("The year is", 2018))
## [1] "The year is 2018"
for(i in 2016:2018){
print(paste("The year is", i))
}
## [1] "The year is 2016"
## [1] "The year is 2017"
## [1] "The year is 2018"
vec <- seq(2, 20, by = 2)
vec
newvec <- vector("numeric", length = length(vec)) # equivalent: numeric(length(vec))
for(i in 1:length(vec)){
newvec[i] <- vec[i]^2
}
newvec
## [1] 4 16 36 64 100 144 196 256 324 400
# advanced: vec^2
x <- 7
if (x < 10){
print("x is less than 10")
}else{
print("x is greater than 10")
}
## [1] "x is less than 10"
age <- sample(1:100, 10)
ageCat <- rep(NA, length(age))
for (i in 1:length(age)) {
if (age[i] <= 35){
ageCat[i] <- "Young"
}else if (age[i] <= 55){
ageCat[i] <- "Middle-Aged"
}else{
ageCat[i] <- "Old"
}
}
age.df <- data.frame(age = age, ageCat = ageCat)
age.df[1:3,]
## age ageCat
## 1 82 Old
## 2 44 Middle-Aged
## 3 95 Old
break
repeat{do this}
repeat{...; break}
. while(condition){do this}
break
. next
break
, but exits top-level of function. Also returns an object from inside your function. for(){create object; return(object)}
Initialize \(tallest\) = \(height_1\)
For each \(element\) in \(H\), do
If \(element > tallest\), then
\(tallest = element\)
end for
return \(tallest\)
myHeights <- c(63, 58, 72, 65)
findTallest <- function(H){
# initialize tallest
tallest <- H[1]
# search through all heights in H
for(height in H){
if(height > tallest){tallest <- height}
}
# spit out the tallest height after for-loop has run
return(tallest)
}