丢弃第一和最后n行 [英] Throw away first and last n rows

查看:120
本文介绍了丢弃第一和最后n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个 data.table ,我想扔掉第一个和最后n行。我想先应用一些过滤,然后截断结果。我知道我可以这样做:

I have a data.table in R where I want to throw away the first and the last n rows. 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?

推荐答案

在这种情况下,你知道一个列( row1 因此使用 length(< any column>)返回未命名临时 data.table / p>

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:

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

这篇关于丢弃第一和最后n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆