简体   繁体   English

将数据框中的所有行从第一个匹配项拖放到最后一行

[英]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.

相关问题 从列表中匹配行的数据框中删除行 - Remove Rows From Data Frame where a Row match from a list 按组选择数据框中的第一行和最后一行 - Select the first and last row by group in a data frame 选择数据框中的第一行和最后一行? - select the first and last row within in a data frame? 在R中循环通过一个数据帧以有条件地生成另一个数据帧,其中第一个数据帧中的每一行有一行或多行 - In R loop through one data frame to generate another data frame conditionally with one or more rows for each row in the first data frame 如何在R中的特定行号或日期之后删除数据框的所有行? - How to drop all rows of data frame after specific row number or date in R? 如何计算数据帧的所有行与r中的最后一行之间的欧几里得距离 - how to calculate Euclidean distance between all rows of a data frame and the last row in r 将数据框中的一行添加到另一数据框中的所有行 - Add one row in a data frame to all rows of another data frame 在 R 中,如果站点和日期在两个数据帧中匹配,则从第一个数据帧中提取行值 - In R, if site and date match in two data frames, pull row values from first data frame 使用 dplyr 从数据框中删除遵循过滤器阈值的所有行 - Drop all rows from data frame that follow a filter threshold using dplyr 循环遍历数据框并使用列值匹配/填充行 - Loop through data frame and match/populate rows with column values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM