在R中找到长度为n的第一个序列

时间:2016-03-15 16:51:01

标签: r

假设我有这样的data.frame

df <- data.frame(signal = c(0, 0, 1, 0, 1, 1, 0, 1, 1, 1))

通过连续n次的数字信号找到第一个信号的最佳方法是什么。例如,如果n = 1,那么我的信号将是第三个元素,我想得到这样的答案:

c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)

对于n = 2,答案是:

c(0, 0, 0, 0, 0, 1, 0, 0, 0, 0)

对于n = 3,最后一个元素是连续3个之后的信号:

c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1)

3 个答案:

答案 0 :(得分:5)

var cart = new Cart();
var item = cart.addItem('e2132865c0a8016500108d9cee411699');
cart.setVariable(item, 'original', request.phone_number);

// set the requested for
var gr = new GlideRecord("sys_user");

gr.addQuery("user_name", request.requested_for);
gr.query();

if (gr.next()) {
  var cartGR = cart.getCart();
  cartGR.requested_for = gr.sys_id;
  cartGR.update();
}

var rc = cart.placeOrder();
response.request_number = rc.number;
response.test = "You ran the Script!";

完整的功能是

x <- c(0, 0, 1, 0, 1, 1, 0, 1, 1, 1)

y <- rle(x)
y$values <- y$lengths * y$values
(y <- inverse.rle(y))
# [1] 0 0 1 0 2 2 0 3 3 3

f <- function(n) {z <- rep(0, length(y)); z[which.max(cumsum(y == n))] <- 1; z}
f(1)
# [1] 0 0 1 0 0 0 0 0 0 0

f(2)
# [1] 0 0 0 0 0 1 0 0 0 0

f(3)
# [1] 0 0 0 0 0 0 0 0 0 1

编辑第2版

g <- function(x, n) {
  y <- rle(x)
  y$values <- y$lengths * y$values
  y <- inverse.rle(y)
  z <- rep_len(0, length(x))
  z[which.max(cumsum(y == n))] <- 1
  z
}
g(x, 1)
g(x, 2)
g(x, 3)

答案 1 :(得分:5)

窗口大小= n的1滚动乘积中的第一个signal是信号的开头,所以

f <- function(x, n){
  y <- numeric(length(x))
  k <- RcppRoll::roll_prod(x, n)
  y[which(k==1)[1] + n-1] <- 1
  y
}

> f(df$signal, 1)
 [1] 0 0 1 0 0 0 0 0 0 0
> f(df$signal, 2)
 [1] 0 0 0 0 0 1 0 0 0 0
> f(df$signal, 3)
 [1] 0 0 0 0 0 0 0 0 0 1

完整性检查

set.seed(1)
signal <- sample(0:1, 10, TRUE)
signal
# [1] 0 0 1 1 0 1 1 1 1 0
f(signal, 3)
# [1] 0 0 0 0 0 0 0 1 0 0
g(signal, 3)
# [1] 1 0 0 0 0 0 0 0 0 0
fun(signal, 3)
Error in 1:which(r$len * r$val == n)[1] : NA/NaN argument

答案 2 :(得分:3)

fun <- function(signal, n) {
  r <- rle(signal == 1)
  replace(numeric(length(signal)), sum(r$l[seq.int(head(which(r$l * r$v == n), 1))]), 1)
}
fun(df$signal, 1)
# [1] 0 0 1 0 0 0 0 0 0 0
fun(df$signal, 2)
# [1] 0 0 0 0 0 1 0 0 0 0
fun(df$signal, 3)
# [1] 0 0 0 0 0 0 0 0 0 1
fun(df$signal, 4)
# [1] 0 0 0 0 0 0 0 0 0 0