Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element of a list by name

Tags:

r

tidyverse

I'm working with a long named list and I'm trying to keep/remove elements that match a certain name, within a tidyverse context, similar to

dplyr::select(contains("pattern"))

However, I'm having issues figuring it out.

library(tidyverse)

a_list <- 
  list(a = "asdfg",
       b = "qwerty",
       c = "zxcvb")

a_list %>% pluck("a") # works
a_list %>% pluck(contains("a")) #does not work

a_list[2:3] # this is what I want
a_list %>% pluck(-"a") # but this does not work
like image 462
kputschko Avatar asked Jan 26 '18 19:01

kputschko


People also ask

How do I remove an item from a list by value?

Remove an item by value: remove() You can remove the first item from the list where its value is equal to the specified value with remove() . If the list contains more than one matching the specified value, only the first is deleted.

How do I remove a specific item from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you remove an element from a list at a specific index?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output.


1 Answers

To remove by name you could use:

a_list %>% purrr::list_modify("a" = NULL)
$`b`
[1] "qwerty"

$c
[1] "zxcvb"

I'm not sure the other answers are using the name of the element, rather than the element itself for selection. The example you gave is slightly confusing since the element 'a' both contains 'a' in it's value AND is called 'a'. So it's easy to get mixed up. To show the difference I'll modify the example slightly.

b_list <- 
  list(a = "bsdfg",
       b = "awerty",
       c = "zxcvb")

b_list %>% purrr::list_modify("a" = NULL)

returns

$`b`
[1] "awerty"

$c
[1] "zxcvb"

but

purrr::discard(b_list,.p = ~stringr::str_detect(.x,"a"))

returns

$`a`
[1] "bsdfg"

$c
[1] "zxcvb"
like image 98
Tom Greenwood Avatar answered Oct 03 '22 06:10

Tom Greenwood