2012-04-11 162 views
4

我在R有一個data.table,我想扔掉第一行和最後n行。我想先應用一些過濾,然後截斷結果。我知道我可以這樣做:丟掉第一行和最後n行

example=data.table(row1=seq(1,1000,1),row2=seq(2, 3000,3)) 
e2=example[row1%%2==0] 
e2[100:(nrow(e2)-100)] 

是否有可能在一行中做到這一點?我認爲是這樣的:

example[row1%%2==0][100:-100] 

當然不工作的這一點,但有它不需要額外的變量簡單的解決方案?

+1

你測試了'e2 [100:length(e2)-100]'這一行嗎?我認爲你的意思是'nrow'而不是'length'('length(DT)'是列的數量),並且需要括號來替換':',它的優先級高於'-'。我將編輯問題和答案...... – 2012-04-13 09:22:20

+0

你是對的,我的例子沒有回覆我的意圖。 – theomega 2012-04-13 09:40:50

回答

2

在你知道這種情況下,存在一列的名稱(row1),所以使用length(<any column>)返回未命名的臨時data.table內的行數:

example=data.table(row1=seq(1,1000,1),row2=seq(2, 3000,3)) 

e2=example[row1%%2==0] 
ans1 = e2[100:(nrow(e2)-100)] 

ans2 = example[row1%%2==0][100:(length(row1)-100)] 

identical(ans1,ans2) 
[1] TRUE 
3
example=data.table(row1=seq(1,1000,1),row2=seq(2, 3000,3)) 
n = 5 
str(example[!rownames(example) %in% 
       c(head(rownames(example), n), tail(rownames(example), n)), ]) 
Classes ‘data.table’ and 'data.frame': 990 obs. of 2 variables: 
$ row1: num 6 7 8 9 10 11 12 13 14 15 ... 
$ row2: num 17 20 23 26 29 32 35 38 41 44 ... 
- attr(*, ".internal.selfref")=<externalptr> 

添加一行代碼版本的選擇標準

str( 
    (res <- example[row1 %% 2 == 0])[ n:(nrow(res)-n), ] 
    ) 
Classes ‘data.table’ and 'data.frame': 491 obs. of 2 variables: 
$ row1: num 10 12 14 16 18 20 22 24 26 28 ... 
$ row2: num 29 35 41 47 53 59 65 71 77 83 ... 
- attr(*, ".internal.selfref")=<externalptr> 

再添加這個版本不使用中間命名值

str( 
example[row1 %% 2 == 0][n:(sum(row1 %% 2==0)-n), ] 
    ) 
Classes ‘data.table’ and 'data.frame': 491 obs. of 2 variables: 
$ row1: num 10 12 14 16 18 20 22 24 26 28 ... 
$ row2: num 29 35 41 47 53 59 65 71 77 83 ... 
- attr(*, ".internal.selfref")=<externalptr>