字符串中有多少个数字是连续的

How many of the numbers are consecutive in a string

提问人:TarJae 提问时间:11/14/2022 更新时间:11/14/2022 访问量:62

问:

有这个向量:

vector <- c("236", "234", "", "12", "24", "3")

[1] "236" "234" ""    "12"  "24"  "3"

我想检查每个元素中有多少个连续的数字。

预期输出:

2 3 0 2 0 0

我不知道该怎么做!

R 数字 序列

评论


答:

6赞 Waldi 11/14/2022 #1

一种可能的解决方案:

sapply(strsplit(vector,""),
       function(x) {s <- sum(diff(as.numeric(x))==1); 
                    if (s) {s+1} else 0})

[1] 2 3 0 2 0 0
4赞 Allan Cameron 11/14/2022 #2

我想这可以完成这项工作:

vector <- c("236", "234", "", "12", "24", "3")

sapply(strsplit(vector, ""), function(x) {
  r <- rle(diff(as.numeric(x) - seq(length(x))))
  if(0 %in% r$values) max(r$lengths[r$values == 0]) + 1 else 0
})
#> [1] 2 3 0 2 0 0

创建于 2022-11-13 使用 reprex v2.0.2

1赞 akrun 11/14/2022 #3

另一种选择

library(matrixStats)
v1 <- rowSums(rowDiffs(as.matrix(read.fwf(textConnection(paste(vector,
   collapse = "\n")), widths = rep(1, 3)))) == 1, na.rm = TRUE)
replace(v1, v1 != 0, v1[v1!=0] + 1)
[1] 2 3 0 2 0 0