-4
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

My input column is on the left in my data frame.I need my output column to look like the 2nd column.any continuous sequence on the left must result with the output of the start of the sequence on the right column. Thank you

2 Answers2

1

Here is a solution with 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
jogo
  • 12,469
  • 11
  • 37
  • 42
0

You can define groups by whether the 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

Data

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)
CPak
  • 13,260
  • 3
  • 30
  • 48