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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With