Catherine Laing
Catherine Laing

Reputation: 657

Extract object from a list based on element name in R

I have a list of 94 matrices, a subset of which is shown here:

 > summary(full_matrix)

            Length Class  Mode   
 Alex_1         64 -none- numeric
 Alex_10      2500 -none- numeric
 Alex_11      2916 -none- numeric
 Alex_12     20736 -none- numeric
 Lily_1        441 -none- numeric
 Lily_10     57600 -none- numeric
 Lily_11     94249 -none- numeric
 Lily_12    167281 -none- numeric
 Lily_13    206116 -none- numeric
 Naima_1       169 -none- numeric
 Naima_10   209764 -none- numeric
 Naima_11   262144 -none- numeric
 Naima_12   209764 -none- numeric
 Naima_13   177241 -none- numeric
 Naima_14   143641 -none- numeric

I'm running some code on each of these matrices, which I can successfully do using lapply(). However, the code runs very slowly and it takes hours and hours to run on the full list. So I want to split up the list by element name. I have successfully done this manually using subset_matrix <- full_matrix[1:4], which in this example will give:

 > summary(subset_matrix)
         Length Class  Mode   
 Alex_1     64  -none- numeric
 Alex_10  2500  -none- numeric
 Alex_11  2916  -none- numeric
 Alex_12 20736  -none- numeric

However this is clunky and will get messy if I make any changes to the previous parts of my script. What I'd like to do is select all elements containing "Alex_", "Lily_", "Naima_", etc, and create sub-lists of these. I thought this solution might work, but it gives me an empty list:

 > matrix_alex <- full_matrix[c("Alex_")] # subset for individual infants
 > summary(matrix_alex)
      Length Class  Mode
  <NA> 0      -none- NULL

Upvotes: 1

Views: 71

Answers (1)

jay.sf
jay.sf

Reputation: 72653

"Alex_" is not a name in your list.

names(full_list)
# [1] "Alex_01"  "Alex_02"  "Alex_03"  "Bella_01" "Bella_02" "Bella_03"

You may want to use grep which looks up for a pattern.

subset_list <- full_list[grep("Alex_", names(full_list))]
# $Alex_01
# [,1]
# [1,]   NA
# 
# $Alex_02
# [,1]
# [1,]   NA
# 
# $Alex_03
# [,1]
# [1,]   NA

Data:

full_list <- list(Alex_01=matrix(),
                  Alex_02=matrix(),
                  Alex_03=matrix(),
                  Bella_01=matrix(),
                  Bella_02=matrix(),
                  Bella_03=matrix())

Upvotes: 1

Related Questions