79168230

Date: 2024-11-07 22:19:02
Score: 1
Natty:
Report link

Alright I wanted a base R solution, and wasn't satisfied with the @Allan Cameron's answer as I wanted something where all matches are grouped together in a final list at the same 'root' level. I didn't want to use unlist to do so, as I want the matched object to be potentially complex table, and don't want to loose there structure. I though that append may do the trick... and after playing a bit with that I think I got something that seemss to work (at list in my and OP's case):

I used Allan names:

get_elements <- function(x, element) {
    newlist=list()
    for(elt in names(x)){
        if(elt == element) newlist=append(newlist,x[elt])
        else if(is.list(x[[elt]])) newlist=append(newlist,get_elements(x[[elt]],element) )
    }
    return(newlist)
}

Less elegant than a lapply (to my taste) but I am not sure I could do what I want with any *apply function... Although I still feel something even simpler and nicer could be done (maybe with do.call?) but can't find it...

Results with OP's list:

> get_elements(l,"user")                                                                                                                                                                                                                   
$user
[1] "UFUNNF8MA"

$user
[1] "UNFUNQ8MA"

$user
[1] "UQKUNF8MA"

> get_elements(l,"type")
$type
[1] "message"

$type
[1] "message"

$type
[1] "message"
Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @Allan
Posted by: Simon C.