kjo kjo - 1 year ago 57
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
, say, by assigning
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
evaluates to a list similar to
above, and that I want to pass the list resulting from dropping the
element from
to some other function
. In this case, applying the method shown above would require the following:

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

I'm looking for a way to pass to
the modified results from
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
function above?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download