I have the following df
df <- structure(list(position = c(44188968, 44188969, 44188970, 44188975,
44188977, 44188978), code1 = c(1, 0, 1, 0, 0, 1)), class = "data.frame", row.names = c(NA,
-6L))
>df
position code1
44188968 1
44188969 0
44188970 1
44188975 0
44188977 0
44188978 1
I would like to add another column code2
(1
if true, 0
otherwise) when the following condition is true:
- for each
position
, check if the otherpositions
are located +/- 3 away. If true, the otherposition
must havecode1 = 1
.
I would then obtain something like below
position code1 code2
44188968 1 1
44188969 0 1
44188970 1 1
44188975 0 0
44188977 0 1
44188978 1 0
Could you please instruct me on how to achieve such table ?
EDIT: I forgot to mention that my data contains NA
values
position code1
44188968 1
44188969 0
44188970 1
44188975 0
44188977 0
44188978 1
NA 1
NA 0
44189323 NA
In case of NA
values, code2
is also NA
Thank you in advance.