英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论