warship
warship

Reputation: 3024

R list extraction with duplicates

I have a nested R list that looks like:

> myList
$name
[1] "John"                         "Sue"
[3] "Bob"                          "Mark"      

$value
[1] "25" "37" "42" "39"

$boolean
[1] "T" "T" "F" "F"

$name
[1] "Joe" "Mary"           

$value
[1] "78" "91"

$boolean
[1] "T"  "T"

I am trying to extract all entries that belong to $name, but since I have multiple $name's, myList$name only returns the first one:

> myList$name
[1] "John"                         "Sue"
[3] "Bob"                          "Mark" 

How can I return:

[1] "John"                         "Sue"                         "Bob"
[3] "Mark"                         "Joe"                         "Mary" 

Upvotes: 0

Views: 47

Answers (1)

akuiper
akuiper

Reputation: 214957

You can use grepl to get the position of the name elements and then extract:

myList <- list(name = c(1,2), value = c(2,3), name = c(4,5))

unlist(myList[grepl('name', names(myList))], use.names = F)
# [1] 1 2 4 5

Or simply:

unlist(myList[names(myList) == 'name'], use.names = F)
# [1] 1 2 4 5

Upvotes: 2

Related Questions