Home > Software design >  R: How do I filter a named list on names present in a vector?
R: How do I filter a named list on names present in a vector?

Time:11-19

I am trying to obtain a subset of a named list, based on element present in another list.

nammedlist<-list( "a"=c(1,2,3,4), "b"=c(2,4,5), "c"=c(9,5,3,2))

selection<-c("a","c")

desired output:

namedlist2<-list( "a"=c(1,2,3,4), "c"=c(9,5,3,2))


I am considering writing a for loop checking for each name if it is present and then extracting it. But their must be a cleaner way to do this.

CodePudding user response:

You can use the names as an index:

nammedlist[selection]

will give you what you want.

Note that you use single brackets, not double brackets. Single brackets mean that you want a subset of the list. Double brackets mean you want to extract an element from the list.

  • Related