dplyr:如何根据特定行在筛选函数中的位置包含它们?
我想根据以下条件在R中选择我的数据的子样本: t1(组的第一行)-t1(组的第一行)>=2 虚拟数据:dplyr:如何根据特定行在筛选函数中的位置包含它们?,r,filter,dplyr,group-by,R,Filter,Dplyr,Group By,我想根据以下条件在R中选择我的数据的子样本: t1(组的第一行)-t1(组的第一行)>=2 虚拟数据: id <- c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2) t1 <- c(4,3,3,2,2,2,1,1,8,8,7,7,7,6,3) df <- data.frame(id, t1) 但这不是我想要的,也许是使用行数()?我想你不需要滞后,但首先应该能帮到你 > df %>% + group_by(id) %>% + fi
id <- c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2)
t1 <- c(4,3,3,2,2,2,1,1,8,8,7,7,7,6,3)
df <- data.frame(id, t1)
但这不是我想要的,也许是使用
行数()
?我想你不需要滞后
,但首先
应该能帮到你
> df %>%
+ group_by(id) %>%
+ filter(first(t1) - t1 >= 2)
# A tibble: 7 x 2
# Groups: id [2]
id t1
<dbl> <dbl>
1 1 2
2 1 2
3 1 2
4 1 1
5 1 1
6 2 6
7 2 3
使用
subset
+ave
> subset(
+ df,
+ ave(t1, id, FUN = function(x) x[1]) - t1 >= 2
+ )
id t1
4 1 2
5 1 2
6 1 2
7 1 1
8 1 1
14 2 6
15 2 3
我认为您不需要
滞后
,但是首先
应该可以帮助您
> df %>%
+ group_by(id) %>%
+ filter(first(t1) - t1 >= 2)
# A tibble: 7 x 2
# Groups: id [2]
id t1
<dbl> <dbl>
1 1 2
2 1 2
3 1 2
4 1 1
5 1 1
6 2 6
7 2 3
使用
subset
+ave
> subset(
+ df,
+ ave(t1, id, FUN = function(x) x[1]) - t1 >= 2
+ )
id t1
4 1 2
5 1 2
6 1 2
7 1 1
8 1 1
14 2 6
15 2 3
在
base R
中,我们还可以
subset(df, (t1[!duplicated(id)][id] -t1) >= 2)
-输出
# id t1
#4 1 2
#5 1 2
#6 1 2
#7 1 1
#8 1 1
#14 2 6
#15 2 3
在
base R
中,我们还可以
subset(df, (t1[!duplicated(id)][id] -t1) >= 2)
-输出
# id t1
#4 1 2
#5 1 2
#6 1 2
#7 1 1
#8 1 1
#14 2 6
#15 2 3