Home > Software design >  Trimming a List Based On Partial Matches
Trimming a List Based On Partial Matches

Time:10-17

I have a list like this :

> my_list

  [1] "https://pizza.ca/login/"                                                                                            
  [2] "https://chocolate.ca/memberships/levels-page/"                                                                          
  [3] "https://www.pizza123.ca/wp-content/"                     
  [4] "https://twitter.com/ddcus"                                                                                                           
  [5] "https://www.facebook.com/"  

I only want to keep elements in this list that contain the term "pizza".

I tried the following code:

new_list = grep("pizza", my_list)

But this is not working. The final answer should look like this:

 [1] "https://pizza.ca/login/"                                                                                                                                                                   
 [2] "https://www.pizza123.ca/wp-content/" 

Any idea how to do this?

Thanks!

CodePudding user response:

new_list <- my_list[grep("pizza", my_list)]

CodePudding user response:

grep returns only the numeric index of the match. If we need the values instead of the index, use value = TRUE (by default it is FALSE)

grep("pizza", my_list, value = TRUE)
  • Related