Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select list element based on their name

Tags:

list

r

I have a named list of vectors that represent events originated from 2 samples, "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 select only the elements of the list that are either from sample "A" or "B". I could go about doing it with a loop but that sort of defies the point of using list when plyr is around. This, and variations, is 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 am getting:

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 on what I am doing wrong is appreciated.

like image 523
fridaymeetssunday Avatar asked Mar 26 '13 19:03

fridaymeetssunday


1 Answers

You can find the pattern in the names of the list, which gives you an index of which ones:

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

And then use it to subset:

 l.temp[grep("_A$", names(l.temp))]
like image 115
mdsumner Avatar answered Oct 05 '22 04:10

mdsumner