簡體   English   中英

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

[英]R: Find unique vectors in list of vectors

我有一個向量列表

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

它可以解決問題,可以將其重寫為單個函數,但是必須有一個更優雅的解決方案。

我們可以sort list元素進行sort ,應用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM