如何从字符向量列表中删除元素?

3

I have list that looks something like this:

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

我希望根据列表元素的名称从每个向量中删除元素,以便最终得到如下结果:
what_i_want <- list(A = LETTERS[2:6], B = LETTERS[c(1, 3:6)], C = LETTERS[c(2,4:7)])

我应该对i_have_this进行哪些操作才能得到i_want_this

我已经使用purrr::map2(what_i_have, names(what_i_have), function(x, y) x == y),得到了相同结构的逻辑向量列表,但是我的大脑超负荷尝试着对what_i_have进行子集处理。

我缺少什么?你能帮忙吗?

额外奖励点数给tidyverse(或base R)解决方案。

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

感谢您的帮助。
2个回答

2

简单来说,

Map(setdiff, have, names(have))

1
只需使用 x[x != y],这将删除与 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

在基本R中,您可以使用Map
Map(function(x, y) x[x != y], what_i_have, names(what_i_have))

1
谢谢,我知道这是一个愚蠢的问题,但我的大脑已经超载了! - mnfn
1
map2(what_i_have, names(what_i_have), ~.x[.x != .y]) map2(what_i_have, names(what_i_have), ~.x[.x != .y]) - hrbrmstr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接