Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove function from list in R?

Tags:

list

r

nonatomic

I have list with two functions:

foo <- function() { print('foo') }
bar <- function() {}
l <- list(foo, bar)

How can I remove function foo without knowing its index?

I've tried this (to get indexes for sub setting):

> which(l == foo)
Error in l == foo : 
  comparison (1) is possible only for atomic and list types

Is there easy way to remove non-atomic from list without looping?

like image 399
jcubic Avatar asked Sep 13 '19 14:09

jcubic


People also ask

How do I remove a function from a list?

The remove() method takes a single element as an argument and removes it from the list. If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.

How do I remove a function in R?

rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function.

How do I remove a value from a variable in R?

To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.

How do I remove a variable from a list?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


1 Answers

Assuming the code in the question, use identical we can get its index like this:

Position(function(fun) identical(fun, foo), l)
## [1] 1

or

which(sapply(l, identical, foo))
## [1] 1

If you know something about the functions you may be able to run them and select based on the output. For the example this works:

Position(function(f) length(f()), l)
## [1] 1

If you have control over the creation of the list an easy approach is to create the list with names:

l2 <- list(foo = foo, bar = bar)
nms <- setdiff(names(l2), "foo")

Removal

If we know that foo is in l once then

l[-ix]

or in the case of l2:

l2[nms]

or use the alternative given by @Gregor:

Filter(function(x) !identical(x, foo), l)

Edge cases

If foo might not be in l you will need to check that condition first. Position and match return NA if there is no match (or specify the nomatch argument to either) and which returns intetger(0) for a no match.

If foo can be in l more than once then use the which alternative above.

Other

Note that which and Filter check every position but match and Position stop after the first match.

like image 197
G. Grothendieck Avatar answered Oct 03 '22 05:10

G. Grothendieck