【问题标题】:R: Find unique vectors in list of vectorsR:在向量列表中查找唯一向量
【发布时间】:2017-04-21 08:53:58
【问题描述】:

我有一个向量列表

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

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

【问题讨论】:

    标签: r list vector unique


    【解决方案1】:

    我们可以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
    

    【讨论】:

    • 谢谢,这更优雅!我最初尝试使用“唯一”和“重复”,但由于处理“NULL”的错误而以某种方式失败。这就像魅力!
    • 这又快又优雅!你能解释一下它是如何工作的吗?
    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多