[英]Drop all rows in a data frame from first match through to last row
I'd like to drop all the rows in a data frame from the first row that matches a condition through to the last row. 我想从匹配条件的第一行到最后一行删除数据框中的所有行。
This is what I've got in base R, to find the row where disp
is 400, and drop that row and all the rows from that row to the last row: 这是我在基准R中得到的内容,找到disp
为400的行,并将该行以及该行中的所有行放到最后一行:
mtcars[-c(which(mtcars$disp == 400):nrow(mtcars)), ]
How can I do this with dplyr and/or data.table? 我该如何使用dplyr和/或data.table?
In dplyr
, you can use cumsum
inside filter
. 在dplyr
,可以在filter
内使用cumsum
。 Once you hit the first 400, cumsum increases to one. 一旦您达到前400,则总和就增加到一。
mtcars%>%
filter(cumsum(disp==400)<1)
Here's the equivalent in data.table
: 这是data.table
的等效data.table
:
mtcars <- as.data.table(mtcars)
mtcars[cumsum(disp==400)<1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.