Select a list item based on their name

I have a named list of vectors that represent events originating from 2 patterns: "A" and "B":

l.temp <- list( SF1_t_A = c(rep(1:10)), SF2_t_A = c(rep(9:15)), SF1_t_B = c(rep(8:12))) l.temp $SF1_t_A [1] 1 2 3 4 5 6 7 8 9 10 $SF2_t_A [1] 9 10 11 12 13 14 15 $SF1_t_B [1] 8 9 10 11 12 

Now I want to select only list items that are either from pattern "A" or "B". I could do this with a loop, but that doesn't match the point of using the list when plyr is around. These and variations are what I've tried so far:

 llply(l.temp , function(l){ if ((unlist(strsplit(names(l), "_"))[3]) == "A"){ return(l)} }) 

This is the error I get:

 Error in unlist(strsplit(names(l), "_")) : error in evaluating the argument 'x' in selecting a method for function 'unlist': Error in strsplit(names(l), "_") : non-character argument 

Help in what I do wrong is appreciated.

+4
source share
1 answer

You can find a template in the list names that gives you an index of the following:

  grep("_A$", names(l.temp)) 

And then use it for a subset:

  l.temp[grep("_A$", names(l.temp))] 
+5
source

All Articles