Search code examples
rlistpurrr

Unique element of a named list


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


Solution

  • Use duplicated on the names too:

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