我有一个很长的数据框,我想找到一个序列的结束和开始。简化
b = c("a","c","a","c","e", "a","c","a","c","a" ,"c","a","c","a","c" ,"d","d","d","d","d")
a = c(0,0,0,0,1, 4,0,0,0,0, 5,1,6,0,0, 0,10,0,0,0)
df = data.frame(a,b)
我想要的是找到所有非零到0和0到非零转换的方法。
我通过使用lapply
调用函数并保存上一次调用的值来完成此操作。
我正在寻找一些更优雅的东西,让我看看行N和行N + 1,或者更好的是我的函数中的行N到行N + M或更好的东西。
答案 0 :(得分:0)
也许这就是你想要的?它可能不优雅,但它应该检测您描述的转换。
> lagn <- function(x, n) { c(rep(NA,n), x[1:(length(x)-n)]) }
> df$c <- lagn(df$a, 1)
# mult ensures one of the item is zero, add ensures one of the item was nonzero
> df[which( (df$a*df$c)==0 & (df$a+df$c)!=0),]
a b c
5 1 e 0
7 0 c 4
11 5 c 0
14 0 a 6
17 10 d 0
18 0 d 10