2

如果我有一个看起来像的逻辑数组

x = c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)

在上面的示例中,获得最内层 TRUE 的最简单方法是在索引 2 和索引 6 处

4

2 回答 2

3

我不确定您的问题是否明确,但在这种特定情况下,rle可以为您提供所需的内容:

> rle(x)$lengths[1]
[1] 2
> rle(x)$lengths[1]+rle(x)$lengths[2]+1
[1] 6
于 2012-12-29T18:36:26.557 回答
1

这可能更强大?如果真假切换两次以上,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 ]
于 2012-12-29T21:38:59.223 回答