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?
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.
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.
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.
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.
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")
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)
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.
Note that which
and Filter
check every position but match
and Position
stop after the first match.
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