sapply

Intermediate R

Filip Schouwenaars

DataCamp Instructor

lapply()

  • Apply function over list or vector
  • Function can return R objects of different classes
  • List necessary to store heterogeneous content
  • However, often homogeneous content
Intermediate R

Cities: lapply()

cities <- c("New York", "Paris", "London", "Tokyo",
            "Rio de Janeiro", "Cape Town")
result <- lapply(cities, nchar)
str(result)
List of 6
 $ : int 8
 $ : int 5
 $ : int 6
 $ : int 5
 $ : int 14
 $ : int 9
Intermediate R

Cities: lapply()

unlist(lapply(cities, nchar))
8  5  6  5 14  9
Intermediate R

Cities: sapply()

cities <- c("New York", "Paris", "London", "Tokyo",
            "Rio de Janeiro", "Cape Town")
unlist(lapply(cities, nchar))
8  5  6  5 14  9
sapply(cities, nchar)
New York   Paris  London   Tokyo  Rio de Janeiro  Cape Town 
       8       5       6       5              14          9 
Intermediate R

Cities: sapply()

sapply(cities, nchar, USE.NAMES = FALSE)
8  5  6  5 14  9
Intermediate R

Cities: sapply()

first_and_last <- function(name) {
  name <- gsub(" ", "", name)
  letters <- strsplit(name, split = "")[[1]]
  c(first = min(letters), last = max(letters))
}
first_and_last("New York")
first  last 
  "e"   "Y"
Intermediate R

Cities: sapply()

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

Unable to simplify?

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

Unable to simplify?

lapply(cities, 
       unique_letters)
[[1]]
[1]"N" "e" "w" "Y" "o" "r" "k"

[[2]]
[1] "P" "a" "r" "i" "s"

[[3]]
[1] "L" "o" "n" "d"

[[4]]
[1] "T" "o" "k" "y"
sapply(cities, unique_letters)
$`New York`
[1]"N" "e" "w" "Y" "o" "r" "k"

$Paris
[1] "P" "a" "r" "i" "s"

$London
[1] "L" "o" "n" "d"

$Tokyo
[1] "T" "o" "k" "y"
Intermediate R

Let's practice!

Intermediate R

Preparing Video For Download...