2
如果我有一個邏輯陣列,看起來像最裏面的真值
x = c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)
什麼以獲得本例中的最內側TRUEs最簡單的方法,前述情況是在索引2和索引6
如果我有一個邏輯陣列,看起來像最裏面的真值
x = c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)
什麼以獲得本例中的最內側TRUEs最簡單的方法,前述情況是在索引2和索引6
我不知道你的問題是明確定義的,但在這種特殊情況下,rle
給你所需要的:
> rle(x)$lengths[1]
[1] 2
> rle(x)$lengths[1]+rle(x)$lengths[2]+1
[1] 6
,這可能是更強大的?如果trues和falses切換兩次以上,rle
將不起作用。
# you could try it on the original vector..
# x <- c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)
# ..but it also works on a more scattered vector
x <- c(TRUE, FALSE , TRUE, FALSE, FALSE, FALSE, FALSE , TRUE, TRUE, TRUE)
# find the position of all TRUEs
true.positions <- which(x)
# find the midpoint of the vector
midpoint <- length(x)/2
# find the smallest distance from the midpoint,
small.dist <- (true.positions - midpoint)
# both above and below
small.dist.above <- min(small.dist[ small.dist >= 0 ])
small.dist.below <- abs(max(small.dist[ small.dist <= 0 ]))
# find the lowest position above the midpoint
lpa <- which(small.dist.above == true.positions - midpoint)
# find the highest position below the midpoint
hpb <- which(small.dist.below == midpoint - true.positions)
# if both are the midpoint, combine them
closest.trues <- unique(c(hpb , lpa))
# return the position in the original vector x
# of the innermost TRUE
true.positions[ closest.trues ]
謝謝!這工作! – by0