使用累积和获取数字的自定义序列的 R 代码是什么?

What is the R code for getting the custom sequence of the numbers using cumulative sum?

Input   Output
1001    1001
1067    1067
1068    1067
1080    1080
1081    1080
1082    1080
1255    1255
1256    1255
1257    1255
1258    1255
1259    1255
1386    1386
1822    1822

我的输入列在数据的左边 frame.I 需要我的输出列看起来像左边的第二个 column.any 连续序列必须以序列开头的输出为结果在右栏上。谢谢

您可以通过是否 diff(Input) > 1.

来定义组
library(dplyr)
df %>%
  group_by(G = cumsum(c(0, diff(Input)) > 1)) %>%
  mutate(Output = min(Input)) %>%
  ungroup() %>%
  select(-G)

# A tibble: 13 x 2
   # Input Output
   # <int>  <dbl>
 # 1  1001   1001
 # 2  1067   1067
 # 3  1068   1067
 # 4  1080   1080
 # 5  1081   1080
 # 6  1082   1080
 # 7  1255   1255
 # 8  1256   1255
 # 9  1257   1255
# 10  1258   1255
# 11  1259   1255
# 12  1386   1386
# 13  1822   1822

数据

df <- read.table(text="Input   Output
1001    1001
1067    1067
1068    1067
1080    1080
1081    1080
1082    1080
1255    1255
1256    1255
1257    1255
1258    1255
1259    1255
1386    1386
1822    1822", header=TRUE)

这是 data.table

的解决方案
library("data.table")
DT <- fread(
"Input  
1001    
1067    
1068    
1080    
1081    
1082    
1255    
1256    
1257    
1258    
1259    
1386    
1822")
DT[, Output:=min(Input), cumsum((c(0, diff(Input))>1))]
DT