9

数値ベクトルのリストがあり、各ベクトルのコピーを1つだけ含むリストを作成する必要があります。同じ関数のlistメソッドがないので、すべてのベクトルを互いにチェックするために適用する関数を作成しました。

F1 <- function(x){

    to_remove <- c()
    for(i in 1:length(x)){
        for(j in 1:length(x)){
            if(i!=j && identical(x[[i]], x[[j]]) to_remove <- c(to_remove,j)
        }
    }
    if(is.null(to_remove)) x else x[-c(to_remove)] 
} 

問題は、入力リストxのサイズが大きくなると、この関数が非常に遅くなることです。これは、forループによる2つの大きなベクトルの割り当てが原因の1つです。長さ15のベクトルで長さ150万のリストに対して、1分未満で実行されるメソッドを望んでいますが、それは楽観的かもしれません。

リスト内の各ベクトルを他のすべてのベクトルと比較するより効率的な方法を知っている人はいますか?ベクトル自体の長さは同じであることが保証されています。

出力例を以下に示します。

x = list(1:4, 1:4, 2:5, 3:6)
F1(x)
> list(1:4, 2:5, 3:6)
4

2 に答える 2

14

@JoshuaUlrichと@thelatemailによると、問題なくll[!duplicated(ll)] 動作します。
したがって、リスト内のすべての要素をチェックしないという考えでsapplyを使用する方法を以前に提案する必要があります(使用する方が理にかなっunique(ll) ていると思うので、その回答を削除しました)unique

効率が目標であるため、これらをベンチマークする必要があります。

# Let's create some sample data
xx <- lapply(rep(100,15), sample)
ll <- as.list(sample(xx, 1000, T))
ll

いくつかのbecnhmarksに対してそれを置く

fun1 <- function(ll) {
  ll[c(TRUE, !sapply(2:length(ll), function(i) ll[i] %in% ll[1:(i-1)]))]
}

fun2 <- function(ll) {
  ll[!duplicated(sapply(ll, digest))]
}

fun3 <- function(ll)  {
  ll[!duplicated(ll)]
}

fun4 <- function(ll)  {
  unique(ll)
}

#Make sure all the same
all(identical(fun1(ll), fun2(ll)), identical(fun2(ll), fun3(ll)), 
    identical(fun3(ll), fun4(ll)), identical(fun4(ll), fun1(ll)))
# [1] TRUE


library(rbenchmark)

benchmark(digest=fun2(ll), duplicated=fun3(ll), unique=fun4(ll), replications=100, order="relative")[, c(1, 3:6)]

        test elapsed relative user.self sys.self
3     unique   0.048    1.000     0.049    0.000
2 duplicated   0.050    1.042     0.050    0.000
1     digest   8.427  175.563     8.415    0.038
# I took out fun1, since when ll is large, it ran extremely slow

最速のオプション:

unique(ll)
于 2012-12-18T01:42:52.030 に答える
11

各ベクトルをハッシュして!duplicated()から、結果の文字ベクトルの一意の要素を識別するために使用できます。

library(digest)  

## Some example data
x <- 1:44
y <- 2:10
z <- rnorm(10)
ll <- list(x,y,x,x,x,z,y)

ll[!duplicated(sapply(ll, digest))]
# [[1]]
#  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
# 
# [[2]]
# [1]  2  3  4  5  6  7  8  9 10
# 
# [[3]]
#  [1]  1.24573610 -0.48894189 -0.18799758 -1.30696395 -0.05052373  0.94088670
#  [7] -0.20254574 -1.08275938 -0.32937153  0.49454570

これが機能する理由を一目で確認するために、ハッシュは次のようになります。

sapply(ll, digest)
[1] "efe1bc7b6eca82ad78ac732d6f1507e7" "fd61b0fff79f76586ad840c9c0f497d1"
[3] "efe1bc7b6eca82ad78ac732d6f1507e7" "efe1bc7b6eca82ad78ac732d6f1507e7"
[5] "efe1bc7b6eca82ad78ac732d6f1507e7" "592e2e533582b2bbaf0bb460e558d0a5"
[7] "fd61b0fff79f76586ad840c9c0f497d1"
于 2012-12-18T00:27:40.517 に答える