## [1] TRUE FALSE FALSE
# (AND operator) Only examinates the first element of each vector
c(TRUE, TRUE, FALSE) && c(TRUE, FALSE, FALSE)## [1] TRUE
# (OR operator) Only examinates the first element of each vector
c(TRUE, TRUE, FALSE) || c(TRUE, FALSE, FALSE)## [1] TRUE
# While loop
ctr <- 2
while(ctr <= 7){
if(ctr == 100){
break
}
print(paste("ctr is equal to", ctr))
ctr <- ctr + 1
}## [1] "ctr is equal to 2"
## [1] "ctr is equal to 3"
## [1] "ctr is equal to 4"
## [1] "ctr is equal to 5"
## [1] "ctr is equal to 6"
## [1] "ctr is equal to 7"
#Another While Example
# Initialize the speed variable
speed <- 88
while (speed > 30) {
print(paste("Your speed is", speed))
# Break the while loop when speed exceeds 80
if (speed > 80 ) {
break
}
if (speed > 48) {
print("Slow down big time!")
speed <- speed - 11
} else {
print("Slow down!")
speed <- speed - 6
}
}## [1] "Your speed is 88"
num_vector <- c(1:15)
for(i in num_vector){
if(i %% 2 == 0){
next
}else{
print(paste(i, "is odd"))
}
}## [1] "1 is odd"
## [1] "3 is odd"
## [1] "5 is odd"
## [1] "7 is odd"
## [1] "9 is odd"
## [1] "11 is odd"
## [1] "13 is odd"
## [1] "15 is odd"
# The nyc list is already specified
nyc <- list(pop = 8405837,
boroughs = c("Manhattan", "Bronx", "Brooklyn", "Queens", "Staten Island"),
capital = FALSE)
# Loop version 1
for(i in nyc){
print(i)
}## [1] 8405837
## [1] "Manhattan" "Bronx" "Brooklyn" "Queens"
## [5] "Staten Island"
## [1] FALSE
## [1] 8405837
## [1] "Manhattan" "Bronx" "Brooklyn" "Queens"
## [5] "Staten Island"
## [1] FALSE
ttt <- matrix(c("O", NA, "X", NA, "O", "O", "X", NA, "X"),
ncol = 3, nrow = 3)
for (i in 1:nrow(ttt)) {
for (j in 1:ncol(ttt)) {
print(paste("On row", i, "and column",j, "the board contains",ttt[i, j]))
}
}## [1] "On row 1 and column 1 the board contains O"
## [1] "On row 1 and column 2 the board contains NA"
## [1] "On row 1 and column 3 the board contains X"
## [1] "On row 2 and column 1 the board contains NA"
## [1] "On row 2 and column 2 the board contains O"
## [1] "On row 2 and column 3 the board contains NA"
## [1] "On row 3 and column 1 the board contains X"
## [1] "On row 3 and column 2 the board contains O"
## [1] "On row 3 and column 3 the board contains X"
# Pre-defined variables
rquote <- "r's internals are irrefutably intriguing"
chars <- strsplit(rquote, split = "")[[1]]
# Initialize rcount
rcount <- 0
# Finish the for loop
for (char in chars) {
if (char == 'r'){
rcount <- rcount + 1
}
if (char == 'u'){
break
}
}
# Print out rcount
print(rcount)## [1] 5
args(function): Shows the arguments of a functionrequire(): the difference with library() function is when youโre trying to load the package that is not yet installed# The vector pioneers has already been created for you
pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857")
# Split names from birth year
split_math <- strsplit(pioneers, split = ":")
# Convert to lowercase strings: split_low
split_low<-lapply(split_math, tolower)
# Take a look at the structure of split_low
str(split_low)## List of 4
## $ : chr [1:2] "gauss" "1777"
## $ : chr [1:2] "bayes" "1702"
## $ : chr [1:2] "pascal" "1623"
## $ : chr [1:2] "pearson" "1857"
# Transform: use anonymous function inside lapply
names <- lapply(split_low, function(x) x[1])
# Transform: use anonymous function inside lapply
years <- lapply(split_low, function(x) x[2])# Generic select function
select_el <- function(x, index) {
x[index]
}
# Use lapply() twice on split_low: names and years
names <- lapply(split_low, select_el, index = 1)
years <- lapply(split_low, select_el, index = 2)
lapply(split_low, function(x) {
if (nchar(x[1]) > 5) {
return(NULL)
} else {
return(x[2])
}
})## [[1]]
## [1] "1777"
##
## [[2]]
## [1] "1702"
##
## [[3]]
## NULL
##
## [[4]]
## NULL
Instead of return a list, sapply returns a named vector
# temp is already defined in the workspace
temp <- rnorm(5)
# Finish function definition of extremes_avg
extremes_avg <- function(x) {
( min(x) + max(x) ) / 2
}
# Apply extremes_avg() over temp using sapply()
sapply(temp, extremes_avg, USE.NAMES = FALSE)## [1] -1.3945295 1.1253849 -2.6295448 1.1234166 -0.6408276
## [[1]]
## [1] -1.394529
##
## [[2]]
## [1] 1.125385
##
## [[3]]
## [1] -2.629545
##
## [[4]]
## [1] 1.123417
##
## [[5]]
## [1] -0.6408276
# temp is already available in the workspace
# Definition of print_info()
print_info <- function(x) {
cat("The average temperature is", mean(x), "\n")
}
# Apply print_info() over temp using sapply()
sapply(temp, print_info)## The average temperature is -1.394529
## The average temperature is 1.125385
## The average temperature is -2.629545
## The average temperature is 1.123417
## The average temperature is -0.6408276
## [[1]]
## NULL
##
## [[2]]
## NULL
##
## [[3]]
## NULL
##
## [[4]]
## NULL
##
## [[5]]
## NULL
## The average temperature is -1.394529
## The average temperature is 1.125385
## The average temperature is -2.629545
## The average temperature is 1.123417
## The average temperature is -0.6408276
## [[1]]
## NULL
##
## [[2]]
## NULL
##
## [[3]]
## NULL
##
## [[4]]
## NULL
##
## [[5]]
## NULL
# temp is already available in the workspace
# Definition of basics()
basics <- function(x) {
c(min = min(x), mean = mean(x), max = max(x))
}
# Apply basics() over temp using vapply()
vapply(temp, basics, numeric(3))## [,1] [,2] [,3] [,4] [,5]
## min -1.394529 1.125385 -2.629545 1.123417 -0.6408276
## mean -1.394529 1.125385 -2.629545 1.123417 -0.6408276
## max -1.394529 1.125385 -2.629545 1.123417 -0.6408276
## [1] 1 4 7 10
## [1] 8 6 4 2
## [1] 8 6 4 2 8 6 4 2
## [1] 8 8 6 6 4 4 2 2
## [1] 8 8 6 6 4 4 2 2
## [1] FALSE
## [1] TRUE
## [1] 8 6 4 2
## [[1]]
## [1] 8
##
## [[2]]
## [1] 6
##
## [[3]]
## [1] 4
##
## [[4]]
## [1] 2
##
## [[5]]
## [1] 2
##
## [[6]]
## [1] 4
##
## [[7]]
## [1] 6
##
## [[8]]
## [1] 8
# The emails vector has already been defined for you
emails <- c("john.doe@ivyleague.edu", "education@world.gov", "dalai.lama@peace.org",
"invalid.edu", "quant@bigdatacollege.edu", "cookie.monster@sesame.tv")
# Use grepl() to match for "edu"
grepl("edu", emails)## [1] TRUE TRUE FALSE TRUE TRUE FALSE
# Use grep() to match for "edu", save result to hits
hits <- grep("edu", emails)
# Subset emails using hits
emails[hits]## [1] "john.doe@ivyleague.edu" "education@world.gov"
## [3] "invalid.edu" "quant@bigdatacollege.edu"
# more advanced regex
# Use grepl() to match for .edu addresses more robustly
grepl("@.*\\.edu$", emails)## [1] TRUE FALSE FALSE FALSE TRUE FALSE
# Use grep() to match for .edu addresses more robustly, save result to hits
hits <- grep("@.*\\.edu$", emails)
# Subset emails using hits
emails[hits]## [1] "john.doe@ivyleague.edu" "quant@bigdatacollege.edu"
# The emails vector has already been defined for you
emails <- c("john.doe@ivyleague.edu", "education@world.gov", "global@peace.org",
"invalid.edu", "quant@bigdatacollege.edu", "cookie.monster@sesame.tv")
# Use sub() to convert the email domains to datacamp.edu
sub("@.*\\.edu$", "@datacamp.edu", emails )## [1] "john.doe@datacamp.edu" "education@world.gov"
## [3] "global@peace.org" "invalid.edu"
## [5] "quant@datacamp.edu" "cookie.monster@sesame.tv"
# Definition of character strings representing dates
str1 <- "May 23, '96"
str2 <- "2012-03-15"
str3 <- "30/January/2006"
# Convert the strings to dates: date1, date2, date3
date1 <- as.Date(str1, format = "%b %d, '%y")
date2 <- as.Date(str2, format = "%Y-%m-%d")
date3 <- as.Date(str3, format = "%d/%B/%Y")
# Convert dates to formatted strings
format(date1, "%A")## [1] NA
## [1] "15"
## [1] NA
# Definition of character strings representing times
str1 <- "May 23, '96 hours:23 minutes:01 seconds:45"
str2 <- "2012-3-12 14:23:08"
# Convert the strings to POSIXct objects: time1, time2
time1 <- as.POSIXct(str1, format = "%B %d, '%y hours:%H minutes:%M seconds:%S")
time2 <- as.POSIXct(str2, format = "%Y-%m-%d %H:%M:%S")
# Convert times to formatted strings
format(time1, "%M")## [1] NA
## [1] "02:23 p. m."