#our group variable
grp <- cumsum(c(TRUE, diff(a) > 1))
#keep only groups with length 1 (i.e. with no neighbor)
i1 <- a[!!!ave(a, grp, FUN = function(i) length(i) > 1)]
#Find the mean of the groups with more than 1 rows,
i2 <- unname(tapply(a, grp, function(i)mean(i[length(i) > 1])))
#Concatenate the above 2 (eliminating NAs from i2) to get final result
c(i1, i2[!is.na(i2)])
#[1] 1.0 5.0 11.0 15.0 24.0 65.0 31.5
4 回答
这是通过
cumsum(c(TRUE, diff(a) > 1))
创建id的另一个想法,其中1
显示间隙阈值,即您也可以将其包装在一个函数中 . 我把间隙留作参数让你可以调整,
DATA:
我有一个基于data.table的解决方案,同样可以翻译成dplyr我猜:
它的作用:如果与以下数字的差异为1,则第一行将neigbours设置为1
我想分组,以便所有neigbours的
neighbour
变量为1 . 我需要在每个组的每一端添加1:然后,我只是在更改
neighbour
值时进行分组,并将值设置为表示它们是否为neihbours并采取独特的 Value 观 . 瞧 .
这是一个
dplyr
版本,也用作分组变量cumsum(c(1,diff(x)!=1))
:这是我的解决方案,它使用行程编码来识别组:
我假设你不推荐在Rcpp中使用简单的C
for
循环 .