7.3 Lists as return type

Given the flexibility of lists, they are the preferred return type of functions returning multiple values. An example is the function sort() that returns a list when using the argument index.return=T.

> z <- c(5,4,3,6,8,1,9,2,7)
> class(z)
[1] "numeric"
> class(sort(z))
[1] "numeric"
> class(sort(z, index.return=T))
[1] "list"

So in case you have wondered in Section 4 (Vectors) why we accessed the rank of sorted elements using the $ operator, you now know it was because sort() returns a named list.

Another common function that returns a list is strsplit(x,split,...) that split strings into substrings based on a provided character vector.

> x <- "Chapter 7. Lists"
> strsplit(x,"\\.")
[[1]]
[1] "Chapter 7" " Lists"   
> strsplit(x,"\\.")[[c(1,2)]]
[1] " Lists"
> strsplit(x," ")
[[1]]
[1] "Chapter" "7."      "Lists"  
> strsplit(x," ")[[c(1,3)]]
[1] "Lists"

In the example above, there are two substrings that can be splitted by using the character “.” (\ needed to double escape special characters), and three substrings with the space character.

7.3.1 Exercises: Lists

See Section 18.0.17 for solutions.

  1. Create a list “holiday” with two character vectors: the first named country with containing “CH”, “USA”, “Japan”, the second named continent containing “Europe”, “The Americas”, “East Asia”.

  2. Create a list with four four elements. 1) the list “holiday” from the exercise above, 2) a character vector “place” containing “mountain” and “beach”, 3) a numerical vector “day” containing the numbers 1.0 through 20.0, and 4) a logical vector “like” containing TRUEand FALSE.

  3. Return the single element “USA” from the previous list using twice [[]] and once []

  4. Return the single character “Europe” using each operator $, [[]] and [] just once

  5. Return the single character “Japan” using only the operator [[]] and only once.

  6. Create a variable “name” and set it to “day”. Use it to extract the element “day” from the list “x”.

  7. Subset the list into a new list containing the “place” and “like” elements.

  8. Create a chracter vector “Chapters” and concatenate 4 strings. 1) first “Chapter 3. R-Scripts” 2) second “Chapter 4. Vectors” 3) “Chapter 5. Matrices” 4) “Chapter 6. Data Frames”. Extract just the word “Data Frames” with no spaces as a character from Chapters.