简体   繁体   English

扔掉第一行和最后一行

[英]Throw away first and last n rows

I have a data.table in R where I want to throw away the first and the last n rows. 我在R中有一个data.table ,我想扔掉第一行和最后一行。 I want to to apply some filtering before and then truncate the results. 我想先应用一些过滤,然后截断结果。 I know I can do this this way: 我知道我可以这样做:

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

Is there a possiblity of doing this in one line? 有可能在一行中这样做吗? I thought of something like: 我想到了类似的东西:

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

This of course does not work, but is there a simpler solution which does not require a additional variable? 这当然不起作用,但有一个更简单的解决方案,不需要额外的变量?

 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> 

Added a one-liner version with the selection criterion 添加了带有选择标准的单行版本

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> 

And further added this version that does not use an intermediate named value 并进一步添加了不使用中间命名值的此版本

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> 

In this case you know the name of one column ( row1 ) that exists, so using length(<any column>) returns the number of rows within the unnamed temporary data.table : 在这种情况下,您知道存在的一列( 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM