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