Intermediate R
Filip Schouwenaars
DataCamp Instructor
lapply()
sapply()
vapply()
cities <- c("New York", "Paris", "London", "Tokyo",
"Rio de Janeiro", "Cape Town")
sapply(cities, nchar)
New York Paris London Tokyo Rio de Janeiro Cape Town
8 5 6 5 14 9
vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)
vapply(cities, nchar, numeric(1))
New York Paris London Tokyo Rio de Janeiro Cape Town
8 5 6 5 14 9
first_and_last <- function(name) {
name <- gsub(" ", "", name)
letters <- strsplit(name, split = "")[[1]]
return(c(first = min(letters), last = max(letters)))
}
sapply(cities, first_and_last)
New York Paris London Tokyo Rio de Janeiro Cape Town
first "e" "a" "d" "k" "a" "a"
last "Y" "s" "o" "y" "R" "w"
vapply(cities, first_and_last, character(2))
New York Paris London Tokyo Rio de Janeiro Cape Town
first "e" "a" "d" "k" "a" "a"
last "Y" "s" "o" "y" "R" "w"
vapply(cities, first_and_last, character(2))
New York Paris London Tokyo Rio de Janeiro Cape Town
first "e" "a" "d" "k" "a" "a"
last "Y" "s" "o" "y" "R" "w"
vapply(cities, first_and_last, character(1))
Error in vapply(cities, first_and_last, character(1)) :
values must be length 1,
but FUN(X[[1]]) result is length 2
vapply(cities, first_and_last, numeric(2))
Error in vapply(cities, first_and_last, numeric(2)) :
values must be type 'double',
but FUN(X[[1]]) result is type 'character'
unique_letters <- function(name) {
name <- gsub(" ", "", name)
letters <- strsplit(name, split = "")[[1]]
unique(letters)
}
sapply(cities, unique_letters)
$`New York`
[1] "N" "e" "w" "Y" "o" "r" "k"
...
$`Cape Town`
[1] "C" "a" "p" "e" "T" "o" "w" "n"
vapply(cities, unique_letters, character(4))
Error in vapply(cities, unique_letters, character(4)) :
values must be length 4,
but FUN(X[[1]]) result is length 7
Intermediate R