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