lapply

Intermediate R

Filip Schouwenaars

DataCamp Instructor

NYC: for

nyc <- list(pop = 8405837, 
            boroughs = c("Manhattan", "Bronx", "Brooklyn",
            "Queens", "Staten Island"), 
            capital = FALSE)
for(info in nyc) {
  print(class(info))
}
"numeric"
"character"
"logical"
Intermediate R

NYC: lapply()

nyc <- list(pop = 8405837, 
            boroughs = c("Manhattan", "Bronx", "Brooklyn",
            "Queens", "Staten Island"), 
            capital = FALSE)
lapply(nyc, class)
$pop
"numeric"
Intermediate R

NYC: lapply()

$boroughs
"character"
$capital
"logical"
Intermediate R

Cities: for

cities <- c("New York", "Paris", "London", "Tokyo",
            "Rio de Janeiro", "Cape Town")
num_chars <- c()
for(i in 1:length(cities)) {
  num_chars[i] <- nchar(cities[i])
}
num_chars
8  5  6  5 14  9
Intermediate R

Cities: lapply()

cities <- c("New York", "Paris", "London", "Tokyo",
            "Rio de Janeiro", "Cape Town")
lapply(cities, nchar)
[[1]]
[1] 8

[[2]]
[1] 5
...
[[6]]
[1] 9
Intermediate R

Cities: lapply()

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

Oil

oil_prices <- 
  list(2.37, 2.49, 2.18, 
       2.22, 2.47, 2.32)
triple <- function(x) {
  3 * x
}
result <- 
  lapply(oil_prices, triple)
str(result)
List of 6
 $ : num 7.11
 $ : num 7.47
 $ : num 6.54
 $ : num 6.66
 $ : num 7.41
 $ : num 6.96
unlist(result)
7.11 7.47 6.54 
6.66 7.41 6.96
Intermediate R
oil_prices <- list(2.37, 2.49, 2.18, 2.22, 2.47, 2.32)
multiply <- function(x, factor) {
  x * factor
}
times3 <- lapply(oil_prices, multiply, factor = 3)
unlist(times3)
7.11 7.47 6.54 6.66 7.41 6.96
times4 <- lapply(oil_prices, multiply, factor = 4)
unlist(times4)
9.48 9.96 8.72 8.88 9.88 9.28
Intermediate R

Let's practice!

Intermediate R

Preparing Video For Download...