命名列表的唯一元素

huangapple go评论77阅读模式
英文:

Unique element of a named list

问题

以下是您要翻译的代码部分:

l <- list(x = c(1, 2), x = c(1, 2), x = c(1, 3), y = c(1,3))
# with unique, it doesn't work. it drops names

我希望的输出是:

list(x = c(1, 2), x = c(1,3), y = c(1,3))

现在,使用:

l %>%
    tibble::enframe() %>%
    dplyr::distinct() %>%
    tibble::deframe()

但它很慢并且需要大量计算。

似乎这个方法接近,但会删除第二个 x 项:

# Partial solution on stack overflow
l[!duplicated(l)]
list(x = c(1,2), y = c(1,3)

感谢您的建议。

英文:

is there a way to return only unique elements of named list

l <- list(x = c(1, 2), x = c(1, 2), x = c(1, 3), y = c(1,3))
# with unique, it doesn't work. it drops names

I'd like the output to be

list(x = c(1, 2), x = c(1,3), y = c(1,3))

For now, using

l %>%
    tibble::enframe() %>%
    dplyr::distinct() %>%
    tibble::deframe()

but it is slow and requires a lot of calculation.

It seems that is close, but drops the second x item

# Partial solution on stack overflow
l[!duplicated(l)]
list(x = c(1,2), y = c(1,3)

Thanks for your advice

答案1

得分: 4

l[!(duplicated(l) & duplicated(names(l)))]
# $x
# [1] 1 2
# 
# $x
# [1] 1 3
# 
# $y
# [1] 1 3
英文:

Use duplicated on the names too:

l[!(duplicated(l) & duplicated(names(l)))]

# $x
# [1] 1 2
# 
# $x
# [1] 1 3
# 
# $y
# [1] 1 3

huangapple
  • 本文由 发表于 2023年5月17日 23:14:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定