R中最长连续数字的长度

时间:2019-02-26 23:31:44

标签: r

我想找到最长连续数字的长度。我编写了以下代码,但在少数情况下并不能提供正确的输出。

    x <- c("1234589","8205","0126789","016","7894", "987645")
lapply(x, function(x)max(rle(cumsum(c(1, diff(as.numeric(strsplit(as.character(x), "")[[1]])) > 1)))$lengths))

我的输出是

[[1]]
[1] 5

[[2]]
[1] 3

[[3]]
[1] 4

[[4]]
[1] 2

[[5]]
[1] 4

[[6]]
[1] 6

正确的输出应为:

[[1]]
[1] 5

[[2]]
[1] 1

[[3]]
[1] 4

[[4]]
[1] 2

[[5]]
[1] 3

[[6]]
[1] 4

3 个答案:

答案 0 :(得分:1)

这里有可能不使用rle

lapply(x, function(s) {
    v <- as.numeric(unlist(strsplit(s, "")))
    max(sapply(split(v, cumsum(c(0, abs(diff(v)) != 1))), length))
})
#[[1]]
#[1] 5
#
#[[2]]
#[1] 1
#
#[[3]]
#[1] 4
#
#[[4]]
#[1] 2
#
#[[5]]
#[1] 3
#
#[[6]]
#[1] 4

答案 1 :(得分:1)

lapply(strsplit(x, ""), function(x)
    with(rle(diff(as.numeric(x)) %in% c(1, -1)),{
        temp = lengths[values]
        1+max(0, temp[which.max(temp)])
    }))
#[[1]]
#[1] 5

#[[2]]
#[1] 1

#[[3]]
#[1] 4

#[[4]]
#[1] 2

#[[5]]
#[1] 3

#[[6]]
#[1] 4

答案 2 :(得分:1)

另一个选择:

lapply(x, function(x) {
  right <- max(rle(abs(c(1, diff(as.numeric(strsplit(as.character(x), "")[[1]])))))$lengths)
  left <- max(rle(abs(c(1, rev(diff(as.numeric(strsplit(as.character(x), "")[[1]]))))))$lengths)
  return(pmax(right, left))
  })

输出:

[[1]]
[1] 5

[[2]]
[1] 1

[[3]]
[1] 4

[[4]]
[1] 2

[[5]]
[1] 3

[[6]]
[1] 4