# use of "grep" to sub list the list based on its items name in R

I have a list of 7 elements. the element names have the pattern p1.abc1 , p1.abc2, p1.abc3 , p2.abc1, p2.abc2,p2.abc3, p2.abc4.

Data
a.list<- list(p1.abc1= c(1:3), p1.abc2=4, p1.abc3=rep(2,4), p2.abc1=1:3, p2.abc2=c(3:7), p2.abc3=rep(9,3),p2.abc4= c(5:9))

I want to sub list this list to become of length 2.
the expected result is b.list as in the image below: I have tried the following code but it did not work:
how can I put these two syntax in loop
a.list[grep("p1.abc", names(a.list))]
a.list[grep("p2.abc", names(a.list))]

b.list<-for( i in 1:2){
a.list[grep("p[i].abc", names(a.list))]
}

``````a.list<- list(p1.abc1= c(1:3), p1.abc2=4, p1.abc3=rep(2,4), p2.abc1=1:3, p2.abc2=c(3:7), p2.abc3=rep(9,3),p2.abc4= c(5:9))

p1_index_in_a <- grep("p1.abc", names(a.list))
p2_index_in_a <- grep("p2.abc", names(a.list))

new.a.list <- list(a.list[p1_index_in_a],
a.list[p2_index_in_a])``````

I want answer within loop or some apply function because my actual list contains more than 7 elements that I put it just as example.

``````library(purrr)
a.list<- list(p1.abc1= c(1:3), p1.abc2=4, p1.abc3=rep(2,4), p2.abc1=1:3, p2.abc2=c(3:7), p2.abc3=rep(9,3),p2.abc4= c(5:9))

my_patterns_to_loop_for <- c("p1","p2")

p_indexes <- list()
for ( p in my_patterns_to_loop_for)
{
p_indexes[[p]] <-grep(p, names(a.list))
}

new.a.list <- map(p_indexes,~a.list[.])``````
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.