Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove an element if it exists for all sub-elements of a list

Tags:

r

I come across lists that I would like to parse before coercing into a data frame. Sometimes I have lists that have elements I'm not expecting. I'd like to be able to remove all of these unexpected elements by name when they arise. Here is an example of a list with an element wackything that I would like removed without having to call the element index or using a for loop through each sub-element.

my_list <- list(person = list(name = "mike", phone = "111-1111"), 
 person = list(name = "lisa", phone = "222-2222", wackything = "PLEASE REMOVE ME"),
 person = list(name = "kimo", phone = "333-3333"))

I would like my final list to look like this:

final_list <- list(person = list(name = "mike", phone = "111-1111"), 
            person = list(name = "lisa", phone = "222-2222"),
            person = list(name = "kimo", phone = "333-3333"))

so that I can corece it to a data frame using

do.call(rbind, lapply(final_list, rbind))
like image 641
cylondude Avatar asked Jun 19 '16 00:06

cylondude


1 Answers

I think you have too many rbinds in your anticipated use. See if this is satisfactory:

> rmwac <- function(x) x[ !names(x) %in% "wackything"]
> do.call(rbind, lapply(my_list, rmwac))
       name   phone     
person "mike" "111-1111"
person "lisa" "222-2222"
person "kimo" "333-3333"

Notice that epi10's perfectly fine answer use a negative sign and that was possible because grep returns numeric values and indexing of lists with numeric values is possible. It is not, however, possible to use the negative sign with character and logical values.

like image 183
IRTFM Avatar answered Sep 22 '22 01:09

IRTFM