2014-11-02 48 views
2

複製行,我可以得到一個data.tabledt使用找到與原

dt[duplicated(dt, by=someColumns)] 

重複排在R不過,我想獲得對重複的行和「非重複」,例如考慮dt :現在

col1, col2, col3 
    A  B C1 
    A  B C2 
    A B1 C1 

dt[duplicated(dt, by=c('col1', "col2"))會給我沿着

東西線

我想給行,它沒有選擇複製一起得到這個,這是答案的

col1, col2, col3 
    A  B C1 
    A  B C2 

速度對比:

> system.time(dt[duplicated(dt2, by = t) | duplicated(dt, by = t, fromLast = TRUE)]) 
    user system elapsed 
    0.008 0.000 0.009 
> system.time(dt[, .SD[.N > 1], by = t]) 
    user system elapsed 
77.555 0.100 77.703 
+0

哪裏這個'by'說法從何而來?在'?duplicated'的幫助頁面中沒有看到任何'by'參數。你是否使用'duplicated()'而不是'base'? – Chase 2014-11-02 20:16:32

+0

@Chase'dt'是一個'data.table',我忘記提及了。 – FooBar 2014-11-02 20:22:27

+0

同樣的邏輯適用,只是更新我的答案,以反映'data.table'實現。 – Chase 2014-11-02 20:29:59

回答

1

我相信這是基本上是this問題的副本,雖然我可以看到你怎麼可能沒有找到它...

...這是一個答案buildi納克關中提到的問題中列出的邏輯:

dt <- read.table(text = "col1 col2 col3 
    A  B C1 
    A  B C2 
    A B1 C1", header = TRUE, stringsAsFactors = FALSE) 


idx <- duplicated(dt[, 1:2]) | duplicated(dt[, 1:2], fromLast = TRUE) 

dt[idx, ] 
#--- 
    col1 col2 col3 
1 A B C1 
2 A B C2 

由於您使用data.table,這可能是你想要的東西:

library(data.table) 
dt <- data.table(dt) 
dt[duplicated(dt, by = c("col1", "col2")) | duplicated(dt, by = c("col1", "col2"), fromLast = TRUE)] 
#--- 
    col1 col2 col3 
1: A B C1 
2: A B C2 
+0

使用你的代碼來處理'data.table',我只輸出:'col1 col2 col3 1:A B C2'。我認爲這是因爲'data.table'的'duplicate'函數不知道'fromLast'。 – FooBar 2014-11-02 20:35:07

+0

@FooBar - 我猜你的data.table已經過期,版本1.9.4明確支持'fromLast'參數:http://www.rdocumentation.org/packages/data.table/functions/duplicated – Chase 2014-11-02 20:54:45

+0

那就是真正。我嚇壞了,但我的版本是'1.9.2','update.packages()'不會更新它,顯然認爲它是最新的。 – FooBar 2014-11-02 21:31:10

2

您可以輕鬆地只是使用.N實現這一點:

dt[, .SD[.N > 1], by = list(col1, col2)] 
## col1 col2 col3 
## 1: A B C1 
## 2: A B C2 

編輯:

您也可以嘗試使用二進制搜索,這是非常有效的,但它似乎像duplicated仍然更高效

setkey(dt[, indx := .N, by = list(col1, col2)], indx)[!J(1)] 
## col1 col2 col3 
## 1: A B C1 
## 2: A B C2 
+0

就配方而言,這個答案是「更好的」。但是,嵌套的邏輯使它比'data.table'的其他解決方案慢8500倍。 – FooBar 2014-11-02 22:35:10

+0

我已經添加了一個更快的二進制搜索解決方案,但我同意'重複'是非常有效的。雖然我真的不明白爲什麼不能只使用谷歌。大通(他自己monanto)只是從他的答案[這裏](http://stackoverflow.com/questions/7854433/finding-all-duplicate-rows-including-elements-with-smaller-subscripts) – 2014-11-03 08:44:56