将数值向量拆分为它包含的自然序列的函数

Die*_*ido 6 recursion integer split r function

我有一个向量如下:

example <- c(1, 2, 3, 8, 10, 11)
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个函数,该函数返回一个输出,就像您从中获得的输出一样:

desired_output <- list(first_sequence = c(1, 2, 3), 
                       second_sequence = 8, 
                       third_sequence = c(10, 11)
                       )
Run Code Online (Sandbox Code Playgroud)

实际上,我想要的是计算我的向量中有多少个序列,以及每个序列的长度。碰巧“desired_ouput”​​中的列表就足够了。

最终结果是构造另一个向量,我们称之为“b”,其中包含以下内容:

b <- c(3, 3, 3, 1, 2, 2)
Run Code Online (Sandbox Code Playgroud)

这背后的现实世界问题是测量 3D 点云中包含的 3D 对象的高度。

我尝试编写一个返回“example_list”中列表的函数和一个直接输出向量“b”的递归函数,但都没有成功。

有人有什么想法吗?非常感谢。

akr*_*run 5

我们可以通过根据相邻元素的值list创建分组来拆分 adiff

out <- split(example, cumsum(c(TRUE, abs(diff(example)) != 1)))
Run Code Online (Sandbox Code Playgroud)

然后,我们得到lengthsreplicate

unname(rep(lengths(out), lengths(out)))
[1] 3 3 3 1 2 2
Run Code Online (Sandbox Code Playgroud)


Ony*_*mbu 5

你可以这样做:

out <- split(example, example - seq_along(example))
Run Code Online (Sandbox Code Playgroud)

要获得长度:

ln <- unname(lengths(out))
rep(ln, ln)
[1] 3 3 3 1 2 2
Run Code Online (Sandbox Code Playgroud)


Tar*_*Jae 4

这里还有一个。不优雅,但采用不同的方法:

  1. 创建示例向量的数据框
  2. 将元素分配给组
  3. 聚合与tapply
example_df <- data.frame(example = example)

example_df$group <- cumsum(ifelse(c(1, diff(example) - 1), 1, 0))

tapply(example_df$example, example_df$group, function(x) x)
Run Code Online (Sandbox Code Playgroud)
$`1`
[1] 1 2 3

$`2`
[1] 8

$`3`
[1] 10 11
Run Code Online (Sandbox Code Playgroud)