R:在向量列表中查找唯一向量

时间:2017-04-21 08:53:59

标签: r list vector unique

我有一个载体列表

list_of_vectors <- list(c("a", "b", "c"), c("a", "c", "b"), c("b", "c", "a"), c("b", "b", "c"), c("c", "c", "b"), c("b", "c", "b"), c("b", "b", "c", "d"), NULL)

对于这个列表,我想知道哪些向量在元素方面是唯一的。也就是说,我想要以下输出

[[1]]
[1] "a" "b" "c"

[[2]]
[1] "b" "b" "c"

[[3]]
[1] "c" "c" "b"

[[4]]
[1] "b" "b" "c" "d"

[[5]]
[1] NULL

R中是否有用于执行此检查的功能?或者我是否需要通过编写函数来做很多变通办法?

我目前不那么优雅的解决方案:

# Function for turning vectors into strings ordered by alphabet
stringer <- function(vector) {
  if(is.null(vector)) {
    return(NULL)
  } else {
    vector_ordered <- vector[order(vector)]
    vector_string <- paste(vector_ordered, collapse = "")
    return(vector_string)
  }
}

# Identifying unique strings
vector_strings_unique <- unique(lapply(list_of_vectors, function(vector) 
stringer(vector)))
vector_strings_unique 

[[1]]
[1] "abc"

[[2]]
[1] "bbc"

[[3]]
[1] "bcc"

[[4]]
[1] "bbcd"

[[5]]
NULL

# Function for splitting the strings back into vectors 
splitter <- function(string) {
  if(is.null(string)) {
    return(NULL)
  } else {
    vector <- unlist(strsplit(string, split = ""))
    return(vector)
  }
}

# Applying function
lapply(vector_strings_unique, function(string) splitter(string))

[[1]]
[1] "a" "b" "c"

[[2]]
[1] "b" "b" "c"

[[3]]
[1] "c" "c" "b"

[[4]]
[1] "b" "b" "c" "d"

[[5]]
[1] NULL

它可以解决这个问题并且可以作为单个函数重写,但必须有一个更优雅的解决方案。

1 个答案:

答案 0 :(得分:5)

我们可以sort list个元素,应用duplicated来获取唯一元素的逻辑索引,并根据该元素对list进行子集

list_of_vectors[!duplicated(lapply(list_of_vectors, sort))]
#[[1]]
#[1] "a" "b" "c"

#[[2]]
#[1] "b" "b" "c"

#[[3]]
#[1] "c" "c" "b"

#[[4]]
#[1] "b" "b" "c" "d"

#[[5]]
#NULL