2

我有一个很长的数据框,我想找到一个序列的结尾和开头。简化

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 行,或者更好的东西。

4

1 回答 1

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
于 2012-04-18T05:01:19.903 回答