简体   繁体   English

在同一列中的某个值之后查找行

[英]Find rows after certain value in same column

I have a column in my dataframe containing ascending numbers which are interrupted by Zeros.我的数据框中有一列包含由零中断的升序数字。
I would like to find all rows which come before a Zero and create a new datatable containing only these rows.我想找到零之前的所有行并创建一个仅包含这些行的新数据表。

My Column: 1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0

What I need: 4, 6我需要什么: 4, 6

Any help would be much appreciated!任何帮助将非常感激! Thanks!谢谢!

Welcome to SO!欢迎来到 SO!
You can try with base R. The idea is to fetch the rownames of the rows before the 0 and subset() the df by them:您可以尝试使用基本 R。这个想法是通过它们获取 0 和subset() df 之前的行的行名:

# your data
df <- data.frame(col = c(1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0))

# an index that get all the rownames before the 0
index <- as.numeric(rownames(df)[df$col == 0]) -1

# here you subset your original df by index: there is also a != 0 to remove the 0 before 0
df_ <- subset(df, rownames(df) %in% index & col !=0) 
df_
   col
4    4
12   6

A dplyr solution:一个 dplyr 解决方案:

library(dplyr)

df %>%
  filter(lead(x) == 0, x != 0)
#>   x
#> 1 4
#> 2 6

Created on 2021-07-08 by the reprex package (v2.0.0)reprex 包( v2.0.0 ) 于 2021 年 7 月 8 日创建

data数据

df <- data.frame(x = c(1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0))

Using base R:使用基础 R:

df <- data.frame(x = c(1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0),
                 y = LETTERS[1:13])

df[diff(df$x)<0,]

   x y
4  4 D
12 6 L

Using Run Lengths in base R. To get the index of x , add the run lengths until 0 value occurs.在基数 R 中使用运行长度。要获得x的索引,请添加运行长度,直到出现 0 值。

x <- c(1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0)

y <- rle(x)  
x[cumsum(y$lengths)][which(y$values == 0) - 1]
# [1] 4 6

暂无
暂无

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

相关问题 如何在R的数据框中的列中查找和删除一定数量的具有相同连续值的行? - How to find and delete a certain number of rows with the same consecutive value in a column in a dataframe in R? 删除某些列值与另一列不匹配的行(全部在同一数据框中) - Removing certain rows whose column value does not match another column (all within the same data frame) R:在满足条件的行中查找一个值,将某些数字添加到该值,然后在该行的另一列中创建一条消息 - R: Find a value in rows met a condition, add certain numbers to the value, and then create a message in that row in another column 如何将 dataframe 的 select 行的值与 R 中某一列中的另一个 dataframe 的值相同 - how to select rows of a dataframe whose value are the same as another dataframe in a certain column in R 仅考虑R中列中具有特定值的行 - Considering only rows with certain value in a column in R 在特定列中的特定值序列之后删除行 - Delete rows after a certain sequence of values in a certain column 在R中某个值之后删除行 - Removing rows after a certain value in R R - 如果第2列中出现特定值,则从第1列中提取多行 - R - Extract multiple rows from column 1 if certain value appears in column 2 根据另一列(对于某些行)更改列的值 - Change the value of a column, based on another column (for certain rows) 如何找到具有相同值的三个连续行 - How to find three consecutive rows with the same value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM