kjo kjo - 2 months ago 5
R Question

How to drop element from named list without assignment?

Suppose I have a named list like

somelist <- list(a = 1, b = 5, c = 3)


I know that I can drop
somelist$b
, say, by assigning
NULL
to it:

somelist$b <- NULL


I suppose this is fine for interactive work, but not so much for programmatic work, because it forces the creation of otherwise superfluous variables.




For example, suppose that
foo(42)
evaluates to a list similar to
somelist
above, and that I want to pass the list resulting from dropping the
b
element from
foo(42)
to some other function
bar
. In this case, applying the method shown above would require the following:

superfluous.variable <- foo(42)
superfluous.variable$b <- NULL
bar(superfluous.variable)
rm(superfluous.variable)





I'm looking for a way to pass to
bar
the modified results from
foo
that does not require these superfluous assignments. The four lines above would collapse to a single line:

bar(drop.item.from.list(foo(42), item.to.drop = "b"))


Does R already have something like the hypothetical
drop.item.from.list
function above?

Answer

You can do that removal on the fly with replace()

replace(somelist, "b", NULL)
# $a
# [1] 1
#
# $c
# [1] 3

It works for multiple variables as well ...

replace(somelist, c("a", "b"), NULL)
# $c
# [1] 3

So just wrap that in bar() and the original list remains intact.

Note: I am not exactly sure what you are doing with foo(42) but you state that the resulting list takes a similar structure, so this should be fine for that.

Comments