gpt4 book ai didi

r - 查找向量中最长的重复元素

转载 作者:行者123 更新时间:2023-12-02 15:26:10 26 4
gpt4 key购买 nike

我想在以下向量中找到等于“1”的连续重复元素的开始和结束索引。向量的值可以等于“1”或 NA。

例如:

out2
[1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
[21] "1" NA NA NA NA NA "1" "1" "1" "1" "1" "1" NA NA NA NA NA NA NA NA

输出应该如下所示

    [,1] [,2]
[1,] 1 21
[2,] 27 32

最佳答案

尝试rle:

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

with(rle(x), {
ok <- !is.na(values)
ends <- cumsum(lengths)[ok]
starts <- ends - lengths[ok] + 1
cbind(starts, ends)
})

给予:

     starts ends
[1,] 1 21
[2,] 27 32

关于r - 查找向量中最长的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com