fridaymeetssunday
fridaymeetssunday

Reputation: 1148

Select list element based on their name

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.

Upvotes: 8

Views: 5218

Answers (1)

mdsumner
mdsumner

Reputation: 29525

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))]

Upvotes: 10

Related Questions