• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Return full list if element to remove from list is not found

Resolved: Return full list if element to remove from list is not found

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have a list for which i can remove element(s) from it based on the presence of a pattern (see this post).

lst <- list(a = 1:4, b = 4:8, c = 8:10) pattern <- "a|c" lstnew <- lst[-grep(pattern, names(lst))] [/code]

The above code removes elements a and c from the list. Great. Sometimes though I have no matching pattern in the list. I then want it to return the full list. If i use the above code, it returns an empty named list.

pattern <- "d|e" lstnew <- lst[-grep(pattern, names(lst))] lstnew named list() [/code]

It seems like an ifelse() is a logical choice to achieve this i.e. if pattern has a match in list, remove elements from list, otherwise return full list. Any suggestions?

Answer:

Use grepl to get a logical vector for subsetting:

lst <- list(a = 1:4, b = 4:8, c = 8:10) pattern <- "a|c" grepl(pattern, names(lst)) #[1] TRUE FALSE TRUE lst[!grepl(pattern, names(lst))] #$b #[1] 4 5 6 7 8 pattern <- "d|e" grepl(pattern, names(lst)) #[1] FALSE FALSE FALSE lst[!grepl(pattern, names(lst))] #$a #[1] 1 2 3 4 # #$b #[1] 4 5 6 7 8 # #$c #[1] 8 9 10 [/code]

If you have better answer, please add a comment about this, thank you!

grep list r
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How can I write CSS selector(s) that apply to table rows for all td elements on that row after a td with a certain class?

01/04/2023

Resolved: How do I use SetWindowText with Unicode in Win32 using PowerShell?

01/04/2023

Resolved: Shopware 400 Status Error “This value is too long. It should have 255 character or less.” When I Try Updating Database Table

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.