I was wondering if there's a way to flag non-consequential numbers? For instance below.
Number
3
4
5
6
10
11
12
16
Is there a way to flag the number before the non-sequential number like so?
Number Flag
3 0
4 0
5 0
6 1
10 0
11 0
12 1
16
etc..
Thank you!
CodePudding user response:
dat$Flag <- c(diff(dat$Number) != 1, NA)
dat
# Number Flag
# 1 3 0
# 2 4 0
# 3 5 0
# 4 6 1
# 5 10 0
# 6 11 0
# 7 12 1
# 8 16 NA
CodePudding user response:
I would use lead()
here:
df$Flag <- as.numeric(lead(df$Number) != df$Number 1)
df
Number Flag
1 3 0
2 4 0
3 5 0
4 6 1
5 10 0
6 11 0
7 12 1
8 16 NA
CodePudding user response:
Here's another option with data.table
:
library(data.table)
setDT(df)[, Flag := (shift(Number, type = "lead") - (Number 1) != 0)]
Output
Number Flag
<int> <int>
1: 3 0
2: 4 0
3: 5 0
4: 6 1
5: 10 0
6: 11 0
7: 12 1
8: 16 NA
Or another option with dplyr
:
library(dplyr)
df %>%
mutate(Flag = (lead(Number) - (Number 1) != 0))
Data
df <- structure(list(Number = c(3L, 4L, 5L, 6L, 10L, 11L, 12L, 16L)), class = "data.frame", row.names = c(NA,
-8L))