vapply

Intermediate R

Filip Schouwenaars

DataCamp Instructor

Recap

  • lapply()
    • apply function over list or vector
    • output = list
  • sapply()
    • apply function over list or vector
    • try to simplify list to array
  • vapply()
    • apply function over list or vector
    • explicitly specify output format
Intermediate R

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
Intermediate R

vapply()

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"
Intermediate R

vapply()

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" 
Intermediate R

vapply() errors

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
Intermediate R

vapply() errors

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'
Intermediate R

unique_letters()

unique_letters <- function(name) {
  name <- gsub(" ", "", name)
  letters <- strsplit(name, split = "")[[1]]
  unique(letters)
}
Intermediate R

vapply() > sapply()

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

Let's practice!

Intermediate R

Preparing Video For Download...