vapply

R für Fortgeschrittene

Filip Schouwenaars

DataCamp Instructor

Zusammenfassung

  • lapply()
    • Funktion auf Liste oder Vektor anwenden
    • Ausgabe = Liste
  • sapply()
    • Funktion auf Liste oder Vektor anwenden
    • Versuch mal, die Liste in ein Array zu verwandeln.
  • vapply()
    • Funktion auf Liste oder Vektor anwenden
    • das Ausgabeformat klar angeben
R für Fortgeschrittene

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
R für Fortgeschrittene

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"
R für Fortgeschrittene

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" 
R für Fortgeschrittene

Fehler bei 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" 
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
R für Fortgeschrittene

Fehler bei vapply()

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'
R für Fortgeschrittene

unique_letters()

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

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
R für Fortgeschrittene

Lass uns üben!

R für Fortgeschrittene

Preparing Video For Download...