Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何删除R数据帧中条件行的以下行?_R_Dataframe_Filtering - Fatal编程技术网

如何删除R数据帧中条件行的以下行?

如何删除R数据帧中条件行的以下行?,r,dataframe,filtering,R,Dataframe,Filtering,我还在学习如何在R中不使用for循环。 我不知道如何将条件和类似迭代的过程结合起来。。。 在一个大数据帧中,我需要消除r=0的所有行,但我还需要消除该行后面的行 例如,在Df数据帧中,我需要去掉第4、5、8和9行 Df x r 1 12 1 2 15 1 3 36 1 4 4 0 5 89 1 6 6 1 7 52 1 8 3 0 9 67 1 10 85 1 计算0行的索引,然后删除这些索引以及每个索引加1 ix <- which(Df$r == 0

我还在学习如何在R中不使用for循环。 我不知道如何将条件和类似迭代的过程结合起来。。。 在一个大数据帧中,我需要消除r=0的所有行,但我还需要消除该行后面的行

例如,在Df数据帧中,我需要去掉第4、5、8和9行

Df
    x r
1  12 1
2  15 1
3  36 1 
4   4 0 
5  89 1
6   6 1
7  52 1
8   3 0
9  67 1
10 85 1

计算0行的索引,然后删除这些索引以及每个索引加1

ix <- which(Df$r == 0)
Df[-c(ix, ix + 1), ]

这里有一个使用dplyr包中的filter和lag函数的选项

    x r
1  12 1
2  15 1
3  36 1
6   6 1
7  52 1
10 85 1
r1 = Df$r != 0 
r2 = c(TRUE, r1[1:(length(r1) - 1)])
Df = Df[r1 & r2,]
library(dplyr)

DF2 <- DF %>% filter(!(r == 0 | lag(r, default = 1) == 0))
DF2
#    x r
# 1 12 1
# 2 15 1
# 3 36 1
# 4  6 1
# 5 52 1
# 6 85 1