R中逻辑数组的最内层真值

时间:2012-12-29 18:32:35

标签: r

如果我有一个类似于

的逻辑数组
x = c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)

在上面的示例中,获取内部最多TRUE的最简单方法是索引2和索引6

2 个答案:

答案 0 :(得分:3)

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

> rle(x)$lengths[1]
[1] 2
> rle(x)$lengths[1]+rle(x)$lengths[2]+1
[1] 6

答案 1 :(得分: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 ]