1

What is the correct way to return a new list with some but not all list elements referred to by name? For example:

$`listA`
[1] 1 2 3 4 5

$listB
[1] "a" "b" "c" "d" "e"

$listC
[1] 25 26 27 28 29 30

should become:

$`listA`
[1] 1 2 3 4 5

$listC
[1] 25 26 27 28 29 30

Here's some data:

list1 <- 1:10
list2 <- letters[1:26]
list3 <- 25:32
mylist <- list(list1,list2,list3)
names(mylist) <- c("listA", "listB", "listC")
2
  • 5
    mylist[c("listA", "listC")] Commented Mar 12, 2019 at 15:00
  • 1
    And if you want to remove some of them do: mylist[c("listA","listB")] = NULL Commented Mar 12, 2019 at 15:25

1 Answer 1

3

The easiest way is to use the [ operator like:

mylist[c("listA", "listC")]

Output:

$`listA`
 [1]  1  2  3  4  5  6  7  8  9 10

$listC
[1] 25 26 27 28 29 30 31 32

Note that when selecting one element from a list using [, the output might not be what we expect:

mylist["listA"]

Output:

$`listA`
 [1]  1  2  3  4  5  6  7  8  9 10

> class(mylist["listA"])
[1] "list"

Here we see that selecting the element "listA" using [ does not return the element itself, but instead, returns a list that contains the "listA" element. If we want to subset the element itself by name, we should use the [[ operator:

mylist[["listA"]]

Output:

[1]  1  2  3  4  5  6  7  8  9 10

> class(mylist[["listA"]])
[1] "integer"

Another difference between [ and [[ is that [[ can only be used to select a single element. For example, the following would not work:

mylist[[c("listA", "listC")]]

Error in mylist[[c("listA", "listC")]] : subscript out of bounds

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.