Intermediate R
Filip Schouwenaars
DataCamp Instructor
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
unlist(lapply(cities, nchar))
8 5 6 5 14 9
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
sapply(cities, nchar, USE.NAMES = FALSE)
8 5 6 5 14 9
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"
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"
unique_letters <- function(name) {
name <- gsub(" ", "", name)
letters <- strsplit(name, split = "")[[1]]
unique(letters)
}
unique_letters("London")
"L" "o" "n" "d"
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