DJC
DJC

Reputation: 1611

Removing list items based on presence of a sub-list

I have a list and I would like to remove any list object with a sublist. In the example below, I would like to remove ob2 and ob5 and keep all other objects.

dat <- list(ob1 = c("a", "b", "c"),
            ob2 = list(a = c("d")),
            ob3 = c("e", "f", "g"),
            ob4 = c("h", "i", "j"),
            ob5 = list(1:3))

Can anyone offer a solution of how to do this?

Upvotes: 1

Views: 56

Answers (1)

akrun
akrun

Reputation: 887128

We can create a condition with sapply (from base R)

dat[!sapply(dat, is.list)]

Or with Filter from base R

Filter(Negate(is.list), dat)

Or with discard

library(purrr)
discard(dat, is.list)

Upvotes: 2

Related Questions