删除与 r 中的特定条件不匹配的行
Removing rows that do not match a certain condition in r
我有一个包含多列的数据框,我想删除不满足特定条件的行。我只想在其中一列的数据框中保留 -1 后跟 1 的行。
示例data.frame
column a column b
1 1 1
2 3 -1
3 8 1
4 10 -1
5 12 1
6 15 1
示例输出:
column a column b
1 3 -1
2 8 1
3 10 -1
4 12 1
有了 dplyr
你可以使用:
library(dplyr)
your_data %>%
filter(
(`column b` == -1 & lead(`column b`) == 1) |
(`column b` == 1 & lag(`column b`) == -1)
)
# column a column b
# 2 3 -1
# 3 8 1
# 4 10 -1
# 5 12 1
使用此输入数据:
your_data = read.table(text = ' "column a" "column b"
1 1 1
2 3 -1
3 8 1
4 10 -1
5 12 1
6 15 1', header = T, check.names = FALSE)
library(tidyverse)
df %>%
group_by(grp = cumsum(lead(df$column_b) == 1 & df$column_b == -1)) %>%
filter(grp > 0, row_number() %in% 1:2)
# A tibble: 4 x 3
# Groups: grp [2]
column_a column_b grp
<int> <int> <int>
1 3 -1 1
2 8 1 1
3 10 -1 2
4 12 1 2
我有一个包含多列的数据框,我想删除不满足特定条件的行。我只想在其中一列的数据框中保留 -1 后跟 1 的行。
示例data.frame
column a column b
1 1 1
2 3 -1
3 8 1
4 10 -1
5 12 1
6 15 1
示例输出:
column a column b
1 3 -1
2 8 1
3 10 -1
4 12 1
有了 dplyr
你可以使用:
library(dplyr)
your_data %>%
filter(
(`column b` == -1 & lead(`column b`) == 1) |
(`column b` == 1 & lag(`column b`) == -1)
)
# column a column b
# 2 3 -1
# 3 8 1
# 4 10 -1
# 5 12 1
使用此输入数据:
your_data = read.table(text = ' "column a" "column b"
1 1 1
2 3 -1
3 8 1
4 10 -1
5 12 1
6 15 1', header = T, check.names = FALSE)
library(tidyverse)
df %>%
group_by(grp = cumsum(lead(df$column_b) == 1 & df$column_b == -1)) %>%
filter(grp > 0, row_number() %in% 1:2)
# A tibble: 4 x 3
# Groups: grp [2]
column_a column_b grp
<int> <int> <int>
1 3 -1 1
2 8 1 1
3 10 -1 2
4 12 1 2