我有一个矩阵列表。对于列表中的每个矩阵,我试图表示当一个值为<100,连续三次。最终,如果事件在序列的任意点连续发生三次,我需要的是每个矩阵的1,如果没有发生,则为0。我提供的代码是更高的分辨率,但我可以减少它以后。下面是我到目前为止编写的代码。由于某种原因,在出现<100次而不是连续3次出场。我认为领导功能是不合适的,但我现在卡住了。我确信一个seq_along for循环可以使用,但我试图保持它的功能。由于
set.seed(24)
list_of_matrices <- replicate(100, matrix(rnorm(1*51), nrow = 1), simplify = FALSE)
test<- lapply(list_of_matrices,function(x){ifelse(x & lead(x,1) & lead(x, 2) < 100, 1, NA)})
这里可以用rle
out <- lapply(list_of_matrices, function(m) {
t(apply(m, 1, function(u) {
rl <- rle(u < 100)
rl$values[(rl$lengths < 3) & rl$values] <- FALSE
as.integer(inverse.rle(rl))
}))
})
与产出
> out[[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 1 1 1 1 1 0
[3,] 1 1 1 1 1 0 1 1 1 0
[4,] 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0
> list_of_matrices[[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 118 114 88 112 100 116 105 119 112 114
[2,] 98 108 87 116 87 97 85 86 83 100
[3,] 87 89 96 95 97 112 85 80 94 105
[4,] 102 105 87 100 91 116 114 85 82 120
[5,] 113 120 92 91 110 99 112 118 93 80
如果它是向量的list
,我们可以通过循环list
rle
lapply(lst1, function(u) {
rl <- rle(u < 100)
rl$values[(rl$lengths < 3) & rl$values] <- FALSE
as.integer(inverse.rle(rl))
})
数据set.seed(24)
list_of_matrices <- replicate(3, matrix(sample(80:120, 5 * 10,
replace = TRUE), ncol = 10, nrow = 5), simplify = FALSE)