Delete an item if it exists for all sub-items in the list

I come across lists that I would like to parse before they are entered into the data frame. Sometimes I have lists that have items that I don't expect. I would like to remove all of these unexpected items by name when they occur. Below is an example of a list with a wackything element that I would like to delete without calling the index of the element or using the for loop through each subitem.

 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 want my last 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 bind it to a data frame using

 do.call(rbind, lapply(final_list, rbind)) 
+5
source share
3 answers

I think you have too many rbinds in your expected 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" 

Please note that epi10 responds very well with a negative sign, and this is possible because grep returns numerical values ​​and it is possible to index lists with numerical values. However, you cannot use a negative sign with symbolic and logical values.

+6
source

bind_rows from the bind_rows package will work, even if not all lists have the same element names. Then you can delete the columns that you do not need.

 library(dplyr) df = bind_rows(my_list) 
  name phone wackything 1 mike 111-1111 NA 2 lisa 222-2222 PLEASE REMOVE ME 3 kimo 333-3333 NA 
 df = df[ , -grep("wackything", names(df))] 
  name phone 1 mike 111-1111 2 lisa 222-2222 3 kimo 333-3333 
+4
source

You can try this. The first step is similar to the 42 answer. Then we use sapply , which returns the matrix, which we then need to transpose.

 my_list <- lapply(my_list, function(x)x[names(x)!= "wackything"]) data.frame(t(sapply(my_list,c)), row.names=NULL) # name phone #1 mike 111-1111 #2 lisa 222-2222 #3 kimo 333-3333 

Another option that gives you the same result.

 data.frame(Reduce(rbind, my_list), row.names=NULL) 

We use row.names=NULL when creating the data frame. You can do this, but this will result in a warning message related to duplicate growth names that we have.

+2
source

All Articles