mnfn
mnfn

Reputation: 85

How can I remove elements from a list of character vectors?

I have list that looks something like this:

what_i_have <- list(A = LETTERS[1:6], B = LETTERS[1:6], C = LETTERS[2:7])

I want to remove elements from each vector according to the name of that list element, so I end up with this:

what_i_want <- list(A = LETTERS[2:6], B = LETTERS[c(1, 3:6)], C = LETTERS[c(2,4:7)])

What manipulations can I do to i_have_this to get to i_want_this?

I have got as far as getting a list of logical vectors in the same structure by using purrr::map2(what_i_have, names(what_i_have), function(x, y) x == y), but my brain is overloaded trying to subset what_i_have.

What am I missing? Can you help?

Bonus points for tidyverse (or base R) solutions.

library(testthat)
test_that("Turn what I have into what I want", {
  expect_equal(what_i_have, what_i_want)
})

Thank you for your help.

Upvotes: 3

Views: 2046

Answers (2)

Sotos
Sotos

Reputation: 51592

Simply,

Map(setdiff, have, names(have))

Upvotes: 2

akuiper
akuiper

Reputation: 214957

Just use x[x != y], this will remove elements that are equal to the names from x:

what_i_get <- purrr::map2(what_i_have, names(what_i_have), function(x, y) x[x != y])
identical(what_i_get, what_i_want)
# [1] TRUE

In base R, you can use Map:

Map(function(x, y) x[x != y], what_i_have, names(what_i_have))

Upvotes: 1

Related Questions