2017-08-25 117 views
1

爲「.SD」功能data.table幫助瞭如何選擇每個組的第一行:data.table選擇每個組的第一行限制爲n-1列?

DT = data.table(x=rep(c("b","a","c"),each=3), v=c(1,1,1,2,2,1,1,2,2), y=c(1,3,6), a=1:9, b=9:1) 
DT 

DT[, .N, by=x]       # number of rows in each group 

這主要適合我,但是當我使用所有列來定義它打破小組,我不明白爲什麼,所以我想知道這是否是一個錯誤。例如:

# Selecting by n-1 columns works: 
DT[, .SD[1], by=c("x", "y", "v", "a")] 
    x y v a b 
1: b 1 1 1 9 
2: b 3 1 2 8 
3: b 6 1 3 7 
4: a 1 2 4 6 
5: a 3 2 5 5 
6: a 6 1 6 4 
7: c 1 1 7 3 
8: c 3 2 8 2 
9: c 6 2 9 1 

# The result of selecting by all columns is not what I expected: 
DT[, .SD[1], by=c("x", "y", "v", "a", "b")] 
Empty data.table (0 rows) of 5 cols: x,y,v,a,b 
+0

實際上,我是想通過行進行重複數據刪除,因此在這裏結束了:https://stackoverflow.com/questions/11792527/filtering-out-duplicated-non-unique-rows-in-data-table但我仍然想知道這是否是一個錯誤。 – zkurtz

+2

'.SD'是data.table的所有列,不包括按列組。如果按所有列進行分組,則不會有'.SD'。 – christoph

+0

一種選擇是創建一個函數來處理這些情況fsd < - function(dt,grps,n)if(length(grps)== ncol(dt))as.data.table(dt )[,tmp:= seq_len(.N)] [, 。(tmp = head(tmp,n)),by = c(grps)] [,tmp:= NULL] [] } else as.data。 table(dt)[,head(.SD,n),by = c(grps)] }; fsd(DT,names(DT),2)' – akrun

回答

2

正如@christoph評論,.SD不包括組列(我相信是出於效率的目的,以免重複存儲組值),你可以這樣做驗證:

unique(DT[, .(name = names(.SD)), by=c('x','v')]$name) 
# [1] "y" "a" "b" 

unique(DT[, .(name = names(.SD)), by=c('x','v','a')]$name) 
# [1] "y" "b" 

所以,如果你按所有列分組,.SD什麼也沒有;以及您的特定情況下,你可以使用unique並通過group變量爲by參數,將根據by刪除列重複:

unique(DT, by=c('x','v')) 

# x v y a b 
#1: b 1 1 1 9 
#2: a 2 1 4 6 
#3: a 1 6 6 4 
#4: c 1 1 7 3 
#5: c 2 3 8 2 

unique(DT, by=c('x','v','y','a','b')) 

# x v y a b 
#1: b 1 1 1 9 
#2: b 1 3 2 8 
#3: b 1 6 3 7 
#4: a 2 1 4 6 
#5: a 2 3 5 5 
#6: a 1 6 6 4 
#7: c 1 1 7 3 
#8: c 2 3 8 2 
#9: c 2 6 9 1 
+2

或者只是'unique(DT)',因爲這使用'by'中的所有列是默認行爲。 –